学术项目中如何读取输入文件的多种数据类型(字符与整数)
如何同时读取文件中的字符(首末行R/W)与整数内容
你的输入文件格式是首行和末行固定为单个字符R或W,中间是整数序列。要同时读取这两类内容,可以参考以下两种可靠的实现方式:
方法一:按类型顺序读取
先读取首行的字符,再循环读取中间的整数,最后读取末行的字符。这种方式利用fscanf的格式匹配特性,同时规避feof循环的常见问题:
#include <stdio.h> #include <stdlib.h> int main() { const char *filename = "your_file.txt"; FILE *inputFile = fopen(filename, "r"); if (inputFile == NULL) { perror("Failed to open file"); return EXIT_FAILURE; } // 读取首行的R/W,注意跳过后续的换行符 char startChar; fscanf(inputFile, "%c\n", &startChar); printf("Start character: %c\n", startChar); // 循环读取整数,用fscanf返回值判断是否读取成功(替代feof) int lineValue; while (fscanf(inputFile, "%d", &lineValue) == 1) { printf("curr line value is -> %d \n", lineValue); } // 读取末行的R/W,格式串前的空格会自动跳过空白字符(如换行) char endChar; fscanf(inputFile, " %c", &endChar); printf("End character: %c\n", endChar); fclose(inputFile); return EXIT_SUCCESS; }
关键细节:
- 读取首字符时用
%c\n,读取后自动跳过换行符,避免后续读取整数时被换行干扰 - 用
fscanf(inputFile, "%d", ...) == 1判断是否成功读取整数,比feof更可靠——feof是在读取失败后才会触发,容易导致最后一次循环重复读取无效内容 - 读取末字符时用
" %c",格式串前的空格会自动跳过所有空白字符(换行、空格等),确保正确读到末行的R/W
方法二:逐行读取并解析
如果文件格式可能有变动(比如整数行夹杂空白行),可以用fgets逐行读取,再通过sscanf判断每行内容类型:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const char *filename = "your_file.txt"; FILE *inputFile = fopen(filename, "r"); if (inputFile == NULL) { perror("Failed to open file"); return EXIT_FAILURE; } char line[256]; // 读取首行 if (fgets(line, sizeof(line), inputFile) != NULL) { // 去掉末尾的换行符 line[strcspn(line, "\n")] = '\0'; printf("Start character: %s\n", line); } // 逐行读取中间内容 while (fgets(line, sizeof(line), inputFile) != NULL) { line[strcspn(line, "\n")] = '\0'; int value; // 尝试解析为整数 if (sscanf(line, "%d", &value) == 1) { printf("curr line value is -> %d \n", value); } else { // 解析失败则为末行的R/W printf("End character: %s\n", line); break; } } fclose(inputFile); return EXIT_SUCCESS; }
关键细节:
strcspn(line, "\n")用来定位换行符的位置,将其替换为\0,避免换行符影响内容解析- 逐行读取的方式更灵活,能处理文件中可能存在的空白行或格式小变动
内容的提问来源于stack exchange,提问作者Mathew Cherian
相关产品推荐
相关产品推荐

