C和C++操作文件的方法

1.C语言

给出自己写的读取和写入文件的函数

void WriteToTXT(struct user myuser)
{
    FILE *fp;
    char ch[100];
    fp = fopen("data.txt", "w");
    if (fp == NULL)
    {
        printf("cannot open data.txt!\n");
        return ;
    }
    fprintf(fp,"%s %d %d %.2f %s",myuser.name,myuser.flag,myuser.score,myuser.right,myuser.grade);
    fclose(fp);
}
void ReadTXT()
{
    FILE *fp;
    fp = fopen("data.txt", "r");
    int i = 0; 
    if (fp == NULL)
    {
        printf("cannot open data.txt!\n");
        return ;
    }
    while(!feof(fp))
    { 
        fscanf(fp,"%s%d%d%f%s",&stu[i].name,&stu[i].flag,&stu[i].score,&stu[i].right,&stu[i].grade);
        i++;
        line = i;
    } 
}

2.C++

        ofstream outfile;
        outfile.open("data.txt");
        if(outfile.is_open())
            cout<<"file is open!!"<<endl;
        else
            cout<<"failed open the file!"<<endl;
        for(int i = 0;i<50;i++)//产生50个x,y数据
        {
            x[i] = this->Xmin+i*dt;
            rand_num = (rand()%5)/5.0;//随机扰动
            y[i] = rand_num + this->gety(x[i]);
            cout<<"x[i]="<<x[i];
            cout<<"  y[i]= "<<y[i]<<endl;
            outfile<< x[i]<<"    ";
            outfile<< y[i]<<endl;
        }
        outfile.close();

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/106983427