[英]reading primitives from file in C
我是C语言的新手,想从文件中读取一些数据。
实际上,我发现了许多读取功能,例如fgetc,fgets等。但是我不知道哪种格式最适合读取以下格式的文件:
0 1500 100.50
1 200 9
2 150 10
我只需要将上面的每一行保存到具有三个数据成员的结构中。
我只需要知道执行此操作的最佳实践,因此对于C编程我还是陌生的。
谢谢。
尝试使用fgets阅读每一行。 每行都可以使用sscanf 。
FILE* f = fopen("filename.txt", "r");
if (f) {
char linebuff[1024];
char* line = fgets(linebuff, 1024, f);
while (line != NULL) {
int first, second;
float third;
if (sscanf(line, "%d %d %g", &first, &second, &third) == 3) {
// do something with them..
} else {
// handle the case where it was not matched.
}
line = fgets(linebuff, 1024, f);
}
fclose(f);
}
这可能会有错误,但这只是为了给您一个示例,说明如何使用这些函数。 确保验证sscanf返回了什么。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
read_file(const char *fname)
{
FILE *f;
char line[1024];
int lineno, int1, int2, nbytes;
double dbl;
if ((f = fopen(fname, "r")) == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
for (lineno = 1; fgets(line, sizeof line, f) != NULL; lineno++) {
int fields = sscanf(line, " %d %d %lg %n", &int1, &int2, &dbl, &nbytes);
if (fields != 3 || (size_t) nbytes != strlen(line)) {
fprintf(stderr, "E: %s:%d: badly formatted data\n", fname, lineno);
exit(EXIT_FAILURE);
}
/* do something with the numbers */
fprintf(stdout, "number one is %d, number two is %d, number three is %f\n", int1, int2, dbl);
}
if (fclose(f) == EOF) {
perror("fclose");
exit(EXIT_FAILURE);
}
}
int main(void)
{
read_file("filename.txt");
return 0;
}
有关代码的一些说明:
fscanf
函数很难使用。 我不得不尝试一段时间,直到正确为止。 必须使用%d
和%lg
之间的空格字符,以便跳过数字之间的任何空格。 这在必须读取换行符的行尾特别重要。 fscanf
和fprintf
的格式字符串在细节上有所不同。 请务必阅读它们的文档。 fgets
的组合一次读取一行,并使用sscanf
解析字段。 我这样做是因为使用fscanf
匹配单个\\n
似乎是不可能的。 -Wall -Wextra
。 这有助于避免一些简单的错误。 更新:我忘了检查一下fgets
每次调用是否都准确地读取了一行。 可能有些行太长而无法放入缓冲区。 应该检查该行始终以\\n
结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.