c++对文件操作的支持(二)

#include <stdio.h>

#include <iostream>

#include <fstream>

using namespace std;

void main()

{       

    int a,b;

    char c;

    ofstream fout("test.txt");

    fout<<0<<" "<<1<<" "<<4<<endl;

    fout<<3<<" "<<4<<" "<<'d'<<endl;

    ifstream fin("test.txt");

    while (!fin.eof())

    {

        fin>>a>>b>>c;

        if(fin.fail()) continue;    //忽略文件中的空行

        cout<<a<<" "<<b<<" "<<c<<endl;

    }

    cin>>a;

}

 

http://www.cplusplus.com/doc/tutorial/files/">http://www.cplusplus.com/doc/tutorial/files/

2.

#include <iostream>

#include <fstream>

using namespace std;



char *getmemory ()

{

    char *p = (char *)malloc(100*sizeof(char));

    return p;

}



void getmemory2(char**p)

{

    *p = (char *)malloc(100*sizeof(char));

}



int main()

{

    static int num =0;

    char *str = NULL;

    //知识点1___给str分配内存的几种方法

    //str= getmemory();

    //getmemory2(&str);

    //str = (char*)malloc(100*sizeof(char));

    str = (char *) calloc(100,sizeof(char));  //区别与malloc: calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据

    //str = new char[100];

    memset(str,0,100);    //    初始化  ; 赋值语句 = strcpy(str,"sadfsa");



    double a = 0.0;    

    int b = 0;

    char c='a';

    ifstream fin("data.txt");

    while (!fin.eof())

    {

        fin.getline(str,1000);

        if (strlen(str) ==0) continue;        //知识点2___对文件中出现空行的处理

        sscanf(str,"%lf,%d,%c",&a , &b ,&c);    //知识点3___将读取的字符串转换为相应的数据类型

        num++;

        if (num ==1)

            cout<<"data.txt中的数据如下"<<endl;

        cout<<a<<","<<b<<","<<c<<endl;

    }

    free(str);

    cout<<"文件共有"<<num<<"数据"<<endl;

    return 0;

}

 

你可能感兴趣的:(文件操作)