简体   繁体   English

fscanf不保存行-C

[英]fscanf not saving line - C

I'm trying to scan a line from a open file pointer, the one passed to the function is stdin. 我正在尝试从打开的文件指针扫描一行,传递给该函数的是stdin。 When I print out the value of input I get (null). 当我打印出输入值时,我得到(空)。 Any ideas why fscanf is not saving the value? 任何想法为什么fscanf不能保存价值? This is the code — also shown below: 这是代码 -也如下所示:

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;
}

You must allocate memory for input before using fscanf(infile,"%s",input); 使用fscanf(infile,"%s",input); 之前,必须为input分配内存fscanf(infile,"%s",input); .

fscanf(infile,"%s",input); asks fscanf to read a string and write it to input . 要求fscanf读取一个字符串并将其写入input Since input has not been assigned a value, let alone a value that points to memory allocated for this, the behavior is not defined. 由于尚未为input分配值,更不用说指向为此分配的内存的值了,因此未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM