【发布时间】:2022-10-09 11:14:07
【问题描述】:
我正在尝试从文件 hw4.data 中读取并查看它是否有名称。用户通过命令行参数输入名称。一切正常,但我无法让文件在函数之间正确传递。作业要求我在 main 中定义文件并在 SCAN 和 LOAD 之间传递它。
#include <stdio.h>
#include <stdlib.h>
struct _data {
char name[20];
long number;
};
int SCAN(FILE *(*stream)) { // skim through the file and find how many entries there are
int size = 0;
char s_temp[100];
long l_temp;
while (1) {
fscanf(*stream, "%s %ld", s_temp, &l_temp);
if (feof(*stream)) break;
size++;
}
return size;
}
struct _data* LOAD(FILE *stream, int size) { // loop through the file and load the entries into the main data array
struct _data* d = malloc(size * sizeof(struct _data));
int i;
for (i = 0; i < size; i++) {
fscanf(stream, "%s %ld", d[i].name, &d[i].number);
}
return d;
}
void SEARCH(struct _data *BlackBox, char* name, int size) { // loop through the array and search for the right name
int i;
int found = 0;
for (i = 0; i < size; i++) {
printf("%s %s\n", BlackBox[i].name, name);
if (strcmp(BlackBox[i].name, name) == 0) {
printf("*******************************************\nThe name was found at the %d entry.\n*******************************************\n", i);
found = 1;
break;
}
}
if (found == 0) {
printf("*******************************************\nThe name was NOT found.\n*******************************************\n");
}
}
void FREE(struct _data* BlackBox, int size) { // free up the dynamic array
free(BlackBox);
}
int main(int argv, char* argc[]) {
if (argv == 2) {
printf("The argument supplied is %s\n", argc[1]);
FILE* file = fopen("./hw4.data", "r");
int size = SCAN(&file);
struct _data* data = LOAD(&file, size);
SEARCH(data, argc[1], size);
fclose(file);
return 0;
} else {
printf("*******************************************\n* You must include a name to search for.*\n*******************************************\n");
return 0;
}
}
这是hw4.data的格式
ron 7774013
jon 7774014
tom 7774015
won 7774016
【问题讨论】:
-
您的编译器应该向您抱怨:您将
FILE **传递给LOAD函数,但它只需要一个FILE *参数。为什么你还是通过&file?那有什么意义呢? -
您必须始终检查
fscanf等函数的返回值,以确保它们成功。 -
另外,除非第一个参数是格式字符串,否则不要使用
printf,否则使用fputs。 -
在
SCAN中,删除feof。替换为:if (fscanf(*stream, "%s %ld", s_temp, &l_temp) != 2) break;请注意,在调用SCAN之后,您应该这样做:rewind(file);。否则,LOAD只会看到 [立即] EOF。而且,正如其他人所提到的,只需将file传递给SCAN/LOAD和不是&file。第三,添加对来自fopen(例如)if (file == NULL) { perror("fopen"); exit(1); }的空返回的检查