c/c++文本文件二进制读写代码段

一:目的

掌握C语言文本文件读写方式;
掌握C语言二进制文件读写方式;
掌握CPP文本文件读写方式;
掌握CPP二进制文件读写方式;

二:C语言文本文件读写

1. 文本文件写入

    
    
  1. //采用C模式对Txt进行写出
  2. void TxtWrite_Cmode()
  3. {
  4. //准备数据
  5. int index[ 50] ;
  6. double x_pos[ 50], y_pos[ 50];
  7. for( int i = 0; i < 50; i ++ )
  8. {
  9. index[i] = i;
  10. x_pos[i] = rand()% 1000 * 0.01 ;
  11. y_pos[i] = rand()% 2000 * 0.01;
  12. }
  13. //写出txt
  14. FILE * fid = fopen( "txt_out.txt", "w");
  15. if(fid == NULL)
  16. {
  17. printf( "写出文件失败!\n");
  18. return;
  19. }
  20. for( int i = 0; i < 50; i ++ )
  21. {
  22. fprintf(fid, "%03d\t%4.6lf\t%4.6lf\n",index[i],x_pos[i],y_pos[i]);
  23. }
  24. fclose(fid);
  25. }
2. 文本文件读取

    
    
  1. //采用C模式对Txt进行读取
  2. void TxtRead_Cmode()
  3. {
  4. FILE * fid = fopen( "txt_out.txt", "r");
  5. if(fid == NULL)
  6. {
  7. printf( "打开%s失败", "txt_out.txt");
  8. return;
  9. }
  10. vector< int> index;
  11. vector< double> x_pos;
  12. vector< double> y_pos;
  13. int mode = 1;
  14. printf( "mode为1,按字符读入并输出;mode为2,按行读入输出;mode为3,知道数据格式,按行读入并输出\n");
  15. scanf( "%d",&mode);
  16. if(mode == 1)
  17. {
  18. //按字符读入并直接输出
  19. char ch; //读取的字符,判断准则为ch不等于结束符EOF(end of file)
  20. while(EOF!=(ch= fgetc(fid)))
  21. printf( "%c", ch);
  22. }
  23. else if(mode == 2)
  24. {
  25. char line[ 1024];
  26. memset(line, 0, 1024);
  27. while(!feof(fid))
  28. {
  29. fgets(line, 1024,fid);
  30. printf( "%s\n", line); //输出
  31. }
  32. }
  33. else if(mode == 3)
  34. {
  35. //知道数据格式,按行读入并存储输出
  36. int index_tmp;
  37. double x_tmp, y_tmp;
  38. while(!feof(fid))
  39. {
  40. fscanf(fid, "%d%lf%lf\n",&index_tmp, &x_tmp, &y_tmp);
  41. index.push_back(index_tmp);
  42. x_pos.push_back(x_tmp);
  43. y_pos.push_back(y_tmp);
  44. }
  45. for( int i = 0; i < index.size(); i++)
  46. printf( "%04d\t%4.8lf\t%4.8lf\n",index[i], x_pos[i], y_pos[i]);
  47. }
  48. fclose(fid);
  49. }

三:C语言二进制文件读写

1. 二进制文件写入

    
    
  1. //采用C模式写二进制文件
  2. void DataWrite_CMode()
  3. {
  4. //准备数据
  5. double pos[ 200];
  6. for( int i = 0; i < 200; i ++ )
  7. pos[i] = i ;
  8. //写出数据
  9. FILE *fid;
  10. fid = fopen( "binary.dat", "wb");
  11. if(fid == NULL)
  12. {
  13. printf( "写出文件出错");
  14. return;
  15. }
  16. int mode = 1;
  17. printf( "mode为1,逐个写入;mode为2,逐行写入\n");
  18. scanf( "%d",&mode);
  19. if( 1==mode)
  20. {
  21. for( int i = 0; i < 200; i++)
  22. fwrite(&pos[i], sizeof( double), 1,fid);
  23. }
  24. else if( 2 == mode)
  25. {
  26. fwrite(pos, sizeof( double), 200, fid);
  27. }
  28. fclose(fid);
  29. }
2.二进制文件读取


    
    
  1. //采用C模式读二进制文件
  2. void DataRead_CMode()
  3. {
  4. FILE *fid;
  5. fid = fopen( "binary.dat", "rb");
  6. if(fid == NULL)
  7. {
  8. printf( "读取文件出错");
  9. return;
  10. }
  11. int mode = 1;
  12. printf( "mode为1,知道pos有多少个;mode为2,不知道pos有多少个\n");
  13. scanf( "%d",&mode);
  14. if( 1 == mode)
  15. {
  16. double pos[ 200];
  17. fread(pos, sizeof( double), 200,fid);
  18. for( int i = 0; i < 200; i++)
  19. printf( "%lf\n", pos[i]);
  20. free(pos);
  21. }
  22. else if( 2 == mode)
  23. {
  24. //获取文件大小
  25. fseek (fid , 0 , SEEK_END);
  26. long lSize = ftell (fid);
  27. rewind (fid);
  28. //开辟存储空间
  29. int num = lSize/ sizeof( double);
  30. double *pos = ( double*) malloc ( sizeof( double)*num);
  31. if (pos == NULL)
  32. {
  33. printf( "开辟空间出错");
  34. return;
  35. }
  36. fread(pos, sizeof( double),num,fid);
  37. for( int i = 0; i < num; i++)
  38. printf( "%lf\n", pos[i]);
  39. free(pos); //释放内存
  40. }
  41. fclose(fid);
  42. }


四:C++文本文件读写

1. 文本文件写入

     
     
  1. //采用CPP模式写txt
  2. void TxtWrite_CPPmode()
  3. {
  4. //准备数据
  5. int index[ 50] ;
  6. double x_pos[ 50], y_pos[ 50];
  7. for( int i = 0; i < 50; i ++ )
  8. {
  9. index[i] = i;
  10. x_pos[i] = rand()% 1000 * 0.01 ;
  11. y_pos[i] = rand()% 2000 * 0.01;
  12. }
  13. //写出txt
  14. fstream f("txt_out.txt", ios::out);
  15. if(f.bad())
  16. {
  17. cout << "打开文件出错" << endl;
  18. return;
  19. }
  20. for( int i = 0; i < 50; i++)
  21. f << setw( 5) << index[i] << "\t" << setw( 10) << x_pos[i] << "\t" <<setw( 10)<< y_pos[i] << endl;
  22. f.close();
  23. }
2.文本文件读取

     
     
  1. //采用CPP模式读取txt
  2. void TextRead_CPPmode()
  3. {
  4. fstream f;
  5. f.open( "txt_out.txt",ios::in);
  6. //文件打开方式选项:
  7. // ios::in    = 0x01, //供读,文件不存在则创建(ifstream默认的打开方式)
  8. // ios::out    = 0x02, //供写,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式)
  9. // ios::ate    = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用
  10. // ios::app    = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入新的内容,指针位置总在最后
  11. // ios::trunc   = 0x10, //在读写前先将文件长度截断为0(默认)
  12. // ios::nocreate = 0x20, //文件不存在时产生错误,常和in或app联合使用
  13. // ios::noreplace = 0x40, //文件存在时产生错误,常和out联合使用
  14. // ios::binary  = 0x80  //二进制格式文件
  15. vector< int> index;
  16. vector< double> x_pos;
  17. vector< double> y_pos;
  18. if(!f)
  19. {
  20. cout << "打开文件出错" << endl;
  21. return;
  22. }
  23. cout<< "mode为1,按字符读入并输出;mode为2,按行读入输出;mode为3,知道数据格式,按行读入并输出"<< endl;
  24. int mode = 1;
  25. cin>>mode;
  26. if( 1== mode)
  27. {
  28. //按字节读入并输出
  29. char ch;
  30. while(EOF != (ch= f.get()))
  31. cout << ch;
  32. }
  33. else if( 2 == mode)
  34. {
  35. //按行读取,并显示
  36. char line[ 128];
  37. int numBytes;
  38. f.getline(line, 128);
  39. cout << line << "\t" << endl ;
  40. f.getline(line, 128);
  41. cout << line << "\t" << endl ;
  42. f.seekg( 0, 0); //跳过字节
  43. //seekg(绝对位置);      //绝对移动,    //输入流操作
  44. //seekg(相对位置,参照位置);  //相对操作
  45. //tellg(); //返回当前指针位置
  46. while(!f.eof())
  47. {
  48. //使用eof()函数检测文件是否读结束
  49. f.getline(line, 128);
  50. numBytes = f.gcount(); //使用gcount()获得实际读取的字节数
  51. cout << line << "\t" << numBytes << "字节" << endl ;
  52. }
  53. }
  54. else if( 3 == mode)
  55. {
  56. //如果知道数据格式,可以直接用>>读入
  57. int index_temp = 0;
  58. double x_pos_temp = 0, y_pos_temp = 0;
  59. while(!f.eof())
  60. {
  61. f >> index_temp >> x_pos_temp >> y_pos_temp ;
  62. index.push_back(index_temp);
  63. x_pos.push_back(x_pos_temp);
  64. y_pos.push_back(y_pos_temp);
  65. cout << index_temp << "\t" << x_pos_temp << "\t" << y_pos_temp << endl;
  66. }
  67. }
  68. f.close();
  69. }



五:C++二进制文件读写


1. 二进制文件写入

     
     
  1. //采用CPP模式写二进制文件
  2. void DataWrite_CPPMode()
  3. {
  4. //准备数据
  5. double pos[ 200];
  6. for( int i = 0; i < 200; i ++ )
  7. pos[i] = i ;
  8. //写出数据
  9. ofstream f("binary.dat",ios::binary);
  10. if(!f)
  11. {
  12. cout << "创建文件失败" << endl;
  13. return;
  14. }
  15. f.write(( char*)pos, 200* sizeof( double)); //fwrite以char *的方式进行写出,做一个转化
  16. f.close();
  17. }
2.二进制文件读取

     
     
  1. //采用CPP模式读二进制文件
  2. void DataRead_CPPMode()
  3. {
  4. double pos[ 200];
  5. ifstream f("binary.dat", ios::binary);
  6. if(!f)
  7. {
  8. cout << "读取文件失败" << endl;
  9. return;
  10. }
  11. f.read(( char*)pos, 200* sizeof( double));
  12. for( int i = 0; i < 200; i++)
  13. cout << pos[i] << endl;
  14. f.close();
  15. }

六 总结

1. C语言读写文件均通过FILE指针执行操作,其中文本文件的读写用fprintf,fscanf,二进制文件的读写用fread,fwrite
2. C++读写文件通过fstream、ifstream、ofstream进行操作,文本文件用<< 和 >> 进行读写,二进制文件用read和write进行读写










  •                     <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">点赞</span>
                        <span class="count">34</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">收藏</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;1582594662_002&quot;}"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>分享</a></li>
                        <!--打赏开始-->
                                                <!--打赏结束-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">文章举报</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/nichengwuxiao">
                    <img src="https://profile.csdnimg.cn/3/2/6/3_nichengwuxiao" class="avatar_pic" username="nichengwuxiao">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/2x/9.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/nichengwuxiao" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">nichengwuxiao</a></span>
                                            </div>
                    <div class="text"><span>发布了22 篇原创文章</span> · <span>获赞 63</span> · <span>访问量 11万+</span></div>
                </div>
                                <div class="right-message">
                                            <a href="https://im.csdn.net/im/main.html?userName=nichengwuxiao" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                        </a>
                                                            <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                    </div>
                            </div>
                    </div>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值