Muh*_*edy 0 c file-io iostream stream
我是C的新手,想要从文件中读取一些数据.
实际上,我发现了许多阅读功能,fgetc,fgets等.但我不知道哪个/组合最好用以下格式读取文件:
0 1500 100.50
1 200 9
2 150 10
Run Code Online (Sandbox Code Playgroud)
我只需要将上面的每一行保存到一个包含三个数据成员的结构中.
我只需要知道这样做的最佳实践,因此我是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);
}
Run Code Online (Sandbox Code Playgroud)
这可能有错误,但它只是给你一个如何使用这些函数的例子.请务必验证sscanf返回的内容.
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |