C++读取txt和保存到txt

  哇,今天又重新用C++来写了一些代码发现自己竟然在类的使用和文件读取和保存上面特别头疼,于是,各种问度娘+各种翻看之前的代码。不禁感叹,自己的代码还是写的太少了,对这些一点都不熟悉。于是,今晚!一定!要!好好!总结!提升!

  •   首先,类的使用方式:
1 Walking *a = new Walking();// a是该类型的指针
2 a->Procesee;
3 Walking a;//a是该类型的一个对象
4 a.Process; 
  •      #define的相关用法:
//简单的 define 定义
#define PI (3.1415926)   //无需等号、分号,需要括号

//带参数的宏定义
#define MAX(a,b) ((a)>(b)?(a):(b))

//定义宏和取消宏
#define
#undef

//使用宏进行条件编译,莫扎特的框架里有用到
#ifdef   (#else)    #endif

//防止重复编译格式,QT里会自动生成
#ifndef _HELLO_H_
#define _HELLO_H
```
//文件内容
···
#endif
  •     文件路径的问题
//最好是英文路径名
//这个写法是错误的!一直用MATLAB,这样写没有问题,突然换到C里面,这样写是不对的
fout1 = fopen("E:footballgaitdataLHip_Yaw.txt","w");

//要用双斜杠
fout1 = fopen("E:\football\gait\data\L\Hip_Yaw.txt","w");
  •           文件读写的方式

C++读取txt和保存到txt

//内容来自:https://www.cnblogs.com/codingmengmeng/p/5545042.html
//第一种方式:ofstream ifstream fstream

//打开文件
//函数open()

public member function  
  
void open ( const char * filename,  
            ios_base::openmode mode = ios_base::in | ios_base::out );  
  
/*
参数:filename   操作文件名
           mode        打开文件的方式
*/
//函数close()
//负责将缓存中的数据排放出来并关闭文件,这个函数一旦被调用,原先的流对象就可以被用来打开其他的文件

C++读取txt和保存到txt

例子:

 1     ifstream ifile1("E:\football\gait\data\trails\L_x.txt",ios::in);
 2     if(!ifile1)
 3          cerr<<"error_O_L"<<endl;
 4     string lineword;
 5     int j = 0;
 6     while (ifile1 >> lineword)
 7     {
 8         sscanf(lineword.c_str(), "%lf", &x_L[j]);//读取到x_L数组里面
 9         printf("%lf
",x_L[j]);
10         j++;  }
11     ifile1.close();
#include "iostream"
#include<fstream> //头文件!!
using namespace std;
void main()
{
    fstream f("d:\try.txt", ios::out);//供写使用,文件不存在则创建,存在则清空原内容
    f << 1234 << ' ' << 3.14 << 'A' << "How are you"; //写入数据
    f.close();//关闭文件以使其重新变为可访问,函数一旦调用,原先的流对象就可以被用来打开其它的文件
    f.open("d:\try.txt", ios::in);//打开文件,供读
    int i;
    double d;
    char c;
    char s[20];
    f >> i >> d >> c;               //读取数据
    f.getline(s, 20);
    cout << i << endl;             //显示各数据
    cout << d << endl;
    cout << c << endl;
    cout << s << endl;
    f.close();
}
//第二种方法
    FILE* fout1 = NULL;
    fout1 = fopen("E:\football\gait\data\L\Hip_Yaw.txt","a+");
    if(!fout1)
        cerr<<"error_S_L"<<endl;
    fprintf(fout1,"%lf
",out[0]*180/PI);
    fclose(fout1);