算法基本思想是:打开文件之后,不断利用fgets函数将文件内容存放到本地存储空间中。这种方法必须要处理fgets插换行符的问题。
#include <string.h> #include <stdio.h> #define OPEN_FILE "test.txt" #define MAX_SIZE 120 char *Delete_Line_Break_and_Save(char *src_buf, char *dst_buf, int start) { strncpy(dst_buf + start, src_buf, strlen(src_buf) - 1); //delete line break, line break is ‘ ’ in Linux. } int main(int argc, char **argv) { FILE *fp = NULL; char *line_p = NULL; char buf[MAX_SIZE] = {0}; char tmp_buf[MAX_SIZE] = {0}; if ( (fp = fopen(OPEN_FILE, "r")) == NULL) { printf("File open error and return!"); return -1; } while (line_p = fgets(tmp_buf, MAX_SIZE, fp)) { Delete_Line_Break_and_Save(tmp_buf,buf, strlen(buf)); } printf("%s ", buf); fclose(fp); return 0; }
上面的代码是直接将换行符删除,之前一直有一个误区,总认为fgets函数都是从文件头开始读取,殊不知fgets函数读取数据具有延续性。另外一种方法是在读取的时候自动跳过换行符,此时我们可以想到sscanf函数,它在遇到换行符或者空格时会自动结束。Delete_Line_Break_and_Save函数可以改写为:
char *Delete_Line_Break_and_Save(char *src_buf, char *dst_buf, int start) { sscanf(src_buf, "%s", dst_buf + start); }
更进一步,我们可以直接利用fscanf函数从文件流中读取数据。
#include <string.h> #include <stdio.h> #define OPEN_FILE "test.txt" #define MAX_SIZE 120 int main(int argc, char **argv) { FILE *fp = NULL; char *line_p = NULL; char buf[MAX_SIZE] = {0}; char tmp_buf[MAX_SIZE] = {0}; if ( (fp = fopen(OPEN_FILE, "r")) == NULL) { printf("File open error and return!"); return -1; } while (fscanf(fp, "%s", buf + strlen(buf)) > 0); printf("%s ", buf); fclose(fp); return 0; }