经典

文件读写之C/C++

Posted by LT on May 9, 2019

一、C

  1. 写文件
    void save()
    {
     int i;
     FILE *fp; //声明fp是FILE型指针
     fp=fopen("通讯录.txt","w"); //输入数据的写入
     for(i=0;i<n;i++)  //n表示有几组数据
         {
             fprintf(fp,"%s %s %s %s %s\n",phone[i].name, phone[i].sex,phone[i].tel,phone[i].address,phone[i].mail);
         }
     fclose(fp);
    }
    
  2. 读文件
    int Re_file()
    {
      int N=0;
      struct s;
      FILE *fp;
      if((fp=fopen("xscjb.txt","r"))==NULL)    /*打开文件*/
      {
      printf("\nCannot open file\n");
      exit(0) ;
      }
      while(fscanf(fp,"%d %s %d %d %d %d ",&s[N].xh,&s[N].name,&s[N].yy,&s[N].Cyy,&s[N].gs,&s[N].pjcj)!=EOF)
       N++;//N记录有多少组数据
      fclose(fp);
    }
    
  3. 读写的两种方式:

    fscanf(dataFile,”%c”,&data[i]); fprintf(data2e,”%c”,data[times]);

fread(ch, sizeof(byte), 1, fp); //读1个byte长度(8个比特)的字符 fwrite(ch, sizeof(byte), 1, fp); //写1个byte长度(8个比特)的字符

  1. 文件定位
    pos = ftell(fp);//当前位置
    fseek(fp, 0, SEEK_SET);
    // SEEK_SET 文件开头
    // SEEK_CUR 文件当前位置
    // SEEK_END 末尾
    

二、C++

  1. 写文件
     int main () {  
      ofstream out("out.txt");  //在<fstream>库中
      if (out.is_open())   
     {  
          out << "This is a line.\n";  
          out << "This is another line.\n";  
          out.close();  
      }  
      return 0;  
     }  
    /*结果: 在out.txt中写入:  
    This is a line.  
    This is another line */
    
  2. 读文件
     int main () {  
        char buffer[256];  
        ifstream in("test.txt");  
        if (! in.is_open())  
        { cout << "Error opening file"; exit (1); }  
        while (!in.eof() )  //循环里可以设置计数器,记录行数
        {  
            in.getline (buffer,100);  //读取一整行
            cout << buffer << endl;  
        }  
        return 0;  
    }  
    /*结果 在屏幕上输出  
     This is a line.  
     This is another line */