我正在尝试从打开的文件指针扫描一行,传递给该函数的是stdin。当我打印出输入值时,我得到(空)。任何想法为什么fscanf不能保存价值?这是the code-也在下面显示:
char *ReadLineFile(FILE *infile){
char *input;
char buf[MAX];
//check if file pointer is at end of file
if(feof(infile))
return NULL;
//scan from file
fscanf(infile,"%s",input);
printf("%s",input);
input = (char *)malloc(strlen(input)+1);
//handle memory allocation errors
if (input == NULL){
printf("Error allocating memory\n");
return "error";
}
fclose(infile);
return input;
}
答案 0 :(得分:1)
您必须先使用input
为fscanf(infile,"%s",input);
分配内存。
fscanf(infile,"%s",input);
要求fscanf
读取一个字符串并将其写入input
。由于尚未为input
分配值,更不用说指向为此分配的内存的值了,因此行为没有定义。