zoukankan      html  css  js  c++  java
  • 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;
    }

    更多参考: http://www.jizhuomi.com/software/340.html

  • 相关阅读:
    [Linux]yum开启rpm包缓存
    [Linux]centOS7-1-1503-x86_64下安装VM-TOOLS
    [Linux]centOS7下RPM安装Perl
    vue 之 pageage.json 和 webpack.config.js
    node 之 apache
    node 之 express
    node 之 基础知识
    npm nvm nrm的关系
    echarts 学习笔记
    git 操作学习
  • 原文地址:https://www.cnblogs.com/lwngreat/p/4226562.html
Copyright © 2011-2022 走看看