0

the following code is to read file from stdin but it cant find the file and I cant find the error. Can someone help.

FILE *file; 
char filename[200];// "ROMAN_in.txt";
char buffer[1000];

if (fgets(filename, sizeof(filename), stdin) == NULL) // from 
stdin(keyboard) to store it in filename 
{
    printf("Error");
    return 1; 
}

file = fopen(filename, "r");

if (file == NULL)
{
    fprintf(stderr, "File %s not found\n", filename);
    return 1;
}
else
{
    while (fgets(buffer, strlen(buffer), file) != NULL)
    {
        printf("%s", buffer);
    }
}
pteran
  • 5
  • 4

1 Answers1

0

In this line:

while (fgets(buffer, strlen(buffer), file) != NULL)

looks like strlen(buffer) returns 0 since buffer in not explicitly initialized global array. Thus it is initialized to 0s. So strlen will return 0.

Probably in your case you should use sizeof(buffer).

P.S.

Try using debugger. You will immediately see in what if condition it goes to the unexpected path.

Edit 1:

Of course, as mentioned by Weather Vane in the comments, fgets returns the string with the \n character (Enter key). You need to get rid of it before using it as a filename (Howto link).

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
  • thanks I changed that but I when I use fopen to open the file, it returns null and printd file not found. Maybe I have to input the filename differently? – pteran Apr 05 '18 at 18:36
  • @pteran I see that 'Weather Vane' wrote you in the comment that you need to get rid of the trailing '\n' after using `fgets` for getting the filename. He is right. – Alex Lop. Apr 05 '18 at 18:38