#include<stdio.h>
#include<stdlib.h>void my(char *ccc, int bbb, FILE*read) { for (size_t i = 0; i < bbb-1; i++) { char teamp= fgetc(read); ccc[i] = teamp; if (feof(read)!= 0) { ccc[i] = '\0'; break; } else if (teamp == '\n') { ccc[i+1] = '\0'; break; } }}void main() { char abc[200] = { 0 }; printf("请输入原始地址"); scanf("%s", abc); FILE*read = fopen(abc, "r"); char teamp[90] = { 0 }; if (teamp!=NULL) { while (feof(read)==0) { my(teamp, sizeof(teamp), read); printf("%s", teamp); } } fclose(read); system("pause");}我们之前学习的fgetc和fputc,一次只能读入或者写出一个char字节。为了能够让这两个函数更加好用一点,我们进行一下封装。fgets和fputs分别是fgetc和fputc的封装.fgets是读入一行.fputs是写出一段文本.
//读入一行字符串void my_fgets(char *p_buffer, int p_maxcount, FILE *p_read) { for (size_t i = 0; i < (p_maxcount - 1); i++) { char l_temp = fgetc(p_read); p_buffer[i] = l_temp; if (l_temp == '\n') { p_buffer[i + 1] = '\0'; break; } else if (feof(p_read) != 0) { p_buffer[i] = '\0'; break; } }
}
#include<stdio.h>#include<stdlib.h>#include<string.h>
void main1() { char l_in_path[200] = { 0 }; printf("请输入要处理的文件:"); scanf("%s", l_in_path); FILE * l_fp_read = fopen(l_in_path, "r"); if (l_fp_read != NULL) { char l_temp[7] = { 0 };
while (feof(l_fp_read) == 0) { fgets(l_temp, sizeof(l_temp), l_fp_read); printf("%s", l_temp); } }
system("pause");}
void main() { char l_out_path[200] = "456.txt"; FILE * l_fp_write = fopen(l_out_path, "w"); if (l_fp_write != NULL) { fputs("你好,我是一名中国人.\n我特别热爱编程!", l_fp_write); } fclose(l_fp_write); system("pause");}