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