【发布时间】:2020-06-14 16:08:42
【问题描述】:
我的程序在加载存在的文件时一直失败并返回:没有这样的文件或目录 其他问题没有任何帮助,因为其他人有不同的问题
incident *fileIn(incident* head){
incident *new;
new = (incident *) malloc(sizeof(incident));
if (new == NULL) {
printf("No memory has been allocated the program will exit\n");
exit(1);
}
FILE *fPointer;
fPointer = fopen("input.txt","r");
if (fPointer == NULL)
{
printf("Could not open file\n");
perror("Err");
exit(1);
}
new->next = new;
char curr_line[300];
while(fgets(curr_line, 10000, fPointer) != NULL){
new = (incident *) malloc(sizeof(incident));
char *token=strtok(curr_line,";/"); /*auth xorizei thn eisodo kathe fora pou petixenei ; h / (gia tis imerominies)*/
strcpy(new->coordinates.area,token);
token=strtok(NULL, ";/");
new->reported.day=atoi(token); /*h atoi metatrepei to string se int*/
token=strtok(NULL, ";/");
new->reported.month=atoi(token);
token=strtok(NULL, ";/");
new->reported.year=atoi(token);
token=strtok(NULL, ";");
strcpy(new->url,token);
incident* tail = head;
if (head->next == head){
head->next = new;
new->next = head;
}
tail = tail->next;
tail->next = new;
new->next = head;
}
fclose(fPointer);
}
文件在那里,我还添加了整个路径,但无济于事。任何帮助将不胜感激。几个小时后我能做什么,我已经尝试了所有我能想到的方法
【问题讨论】:
-
没有足够的信息来回答。请构造一个minimal reproducible example,在其中显示您如何调用该程序。
-
您必须小心大小写...确保在任何地方都使用小写字母。相对路径没问题...只要确保您的文件与 C 文件位于同一目录中...然后它应该可以工作...
-
小花絮:在 C 中使用
new作为变量名是合法的,但是在转换为 C++ 时会成为一个绊脚石,因此将其视为保留字也不错。 -
肯定
fgets(curr_line, sizeof("input.txt"), fPointer)是错误的;应该是sizeof curr_line。 -
incident *new; if (new == NULL) {具有未定义的行为,您期望这样做是什么?可能缺少malloc...