写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用

1. C++

 读取文件

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 int main(){
 5     const char* in_file = "input_file_name";
 6     const char* out_file = "output_file_name";
 7 
 8     FILE *p_in = fopen(in_file, "r");
 9     if(!p_in){
10         printf("open file %s failed!!!", in_file);
11         return -1;
12     }
13         
14     FILE *p_out = fopen(out_file, "w");
15     if(!p_in){
16         printf("open file %s failed!!!", out_file);
17         if(!p_in){
18             fclose(p_in);
19         }
20         return -1;
21     }
22 
23     char buf[2048];
24     //按行读取文件内容
25     while(fgets(buf, sizeof(buf), p_in) != NULL) {
26         //写入到文件
27         fwrite(buf, sizeof(char), strlen(buf), p_out);
28     }
29 
30     fclose(p_in);
31     fclose(p_out);
32     return 0;
33 }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
猜你喜欢
  • 2021-08-16
  • 2021-08-01
  • 2021-07-11
  • 2022-02-16
  • 2021-05-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案