以下代码的行为与预期不符。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
struct dest
{
char filename[20], keyword[20];
bool opened;
FILE * file;
};
void display_data(const struct dest p) {
printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}
int main(int argc, char const *argv[])
{
// declaring variables
float lon, lat;
char info[80];
FILE *reader;
// checking required arguments
if ((argc+1) % 2 || argc < 2) {
fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
return 2;
}
// opening the reader
if (!(reader = fopen(argv[1], "r"))) {
fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
return 2;
}
// creating important globals
const short pairs = (argc-3)/2;
struct dest data[pairs];
struct dest other;
strcpy(other.filename, argv[2]);
other.opened = false;
// gathering data
short times = 4;
for(short i = 4; i < argc; i += 2) {
data[i-times].opened = false;
strcpy(data[i-times].keyword, argv[i-1]);
strcpy(data[i-times].filename, argv[i]);
times += 1;
}
// finally, scanning the file ..
struct dest *use_f; // pointer for the wanted destination ..
bool known;
while (fscanf(reader, "%f,%f,%79[^\n]", &lat, &lon, info)) {
// deciding which file to use ..
known = false;
for(short i=0; i < pairs; ++i) {
if (strstr(info, data[i].keyword)) {
known = true;
use_f = &data[i];
}
}
if (!(known)) {
use_f = &other;
}
// checking the file ..
if (!((*use_f).opened)) {
(*use_f).file = fopen((*use_f).filename, "w");
(*use_f).opened = true;
}
// writing to the file ..
fprintf((*use_f).file, "%f,%f,%s\n", lat, lon, info);
}
// closing all data streams, and informing user ..
for (short i=0; i < pairs; ++i) {
display_data(data[i]);
if (data[i].opened) {
fclose(data[i].file);
data[i].opened = false;
}
}
fclose(reader);
fclose(other.file);
return 0;
}
用于运行它的命令是..
./分类spooky.csv other.csv UFO UFOS.csv#我根本没有输出
似乎while循环实际上并没有结束,这很神秘,因为文件(spooky.csv)只有11行!
30.685163,-68.137207,类型=雪人
28.304380,-74.575195,类型= UFO
29.132971,-71.136475,类型=船舶
28.343065,-62.753906,类型=埃尔维斯
27.868217,-68.005371,类型= Goatsucker
30.496017,-73.333740,类型=消失
26.224447,-71.477051,类型= UFO
29.401320,-66.027832,类型=船舶
37.879536,-69.477539,类型=埃尔维斯
22.705256,-68.192139,类型=埃尔维斯
27.166695,-87.484131,类型=埃尔维斯
它只是继续写入other.file,但我不知道为什么..
程序根本没有结束,有人可以向我解释一下吗?
答案 0 :(得分:4)
从fscanf()
联机帮助页:“如果在发生任何转换(例如文件结束)之前发生输入故障,则返回值EOF。”
这是一个提示...... EOF不等于0.你的while循环永远不会终止。