-1

I'm trying to scan a line from a open file pointer, the one passed to the function is stdin. When I print out the value of input I get (null). Any ideas why fscanf is not saving the value? 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;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Please put the code into the question, not in a link somewhere offsite. Copy'n'paste the code (after making sure there are no tabs in it) and then select it and use the **`{}`** button above the edit box to indent as 'code'. Remember that `scanf()` in general doesn't care much about line boundaries, and the `%s` conversion specification skips white space (including newlines) and stops at the first white space after it gets something that isn't white space. If you want lines of input, use `fgets()` — or on POSIX systems, use `getline()`. – Jonathan Leffler Jan 28 '19 at 03:16
  • Possible duplicate of [why scanf scans a null value](https://stackoverflow.com/questions/25765644/why-scanf-scans-a-null-value) –  Jan 28 '19 at 03:30
  • 1
    Your pointer `input` isn't initialized; your character array `buf` is unused. Both are problems — one serious (crashworthy) and the other minor. You should check the result of `fscanf()` — the test with `feof()` is barely helpful (it ensures that you return `NULL` if the system already encountered EOF on the file stream, but tells you nothing about whether the `fscanf()` will encounter it when called. – Jonathan Leffler Jan 28 '19 at 03:33

1 Answers1

1

You must allocate memory for input before using fscanf(infile,"%s",input);.

fscanf(infile,"%s",input); asks fscanf to read a string and write it to 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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312