Damani A Philip Damani A Philip - 12 days ago 4
C Question

Using Fgets in two ways

I looked through some "FGETS" questions before posting, and what i gathered is it may be a new line character thats causing the issue for the manual input.

int main ( int argc, char *argv[] ){

char temp[1000];
FILE *user_file;

printf("Starting....\n"); //Used for user visual.


if(argc == 2){ //open file
user_file = fopen(argv[1],"r");
if( user_file == NULL ){
printf("No file was found.");
exit(2);
}else{
fgets(temp,strlen(temp),user_file);
}
}else if( argc > 2 ){ // Will exit if arguments are greater than 2.
printf("Maximum args 2.\n");
exit(1);
}else{
printf("File was not provided, please enter the text to convert.\n"); //If the user doesnt provide a file allow manual input.
fgets(temp,strlen(temp),stdin);
}

printf("%s\n",temp);


return 0;
}//End main


Questions:


  1. Why is fgets not opening the txt file I provide it with on the cmd line, and storing it to the temp array?

  2. Why is Fgets being skipped over in the "else" statment if the file is not provided?

  3. Why is print being skipped over in both instances?



Hey and by the way thank you very much for the assistance.
If you know a similar question that has been asked, can you post it in the comments so I can read it.

Dai Dai
Answer

Your code has multiple problems.

Here's the first problem:

char temp[1000];

Your buffer declaration does not initialize the buffer's contents - so the value of each char value will be whatever was in the raw memory previously. In C most strings are "null-terminated" so having a terminating NULL (0 - zero) is important otherwise you can run into buffer-overruns.

The "best" approach is to zero-out (zero-initialize) the array/buffer before you use it, like so (in C99):

char temp[1000] = {0};

...this way temp will contain all 0 values (NULL) so anything written to it (provided it's no longer than 999 bytes) will automatically have a null-terminator (though fgets will append a terminating 0 value, but not every function in C does this).

The second problem is related to the first: you're using the runtime string-length function strlen to get the size of the strlen buffer. This is incorrect as the buffer sized is fixed at compile-time to 1000. The strlen will return the index of the first 0 (NULL) char value, which is undefined behavior at this point because you haven't zero-initialized the buffer anyway (so it could return 0 immediately if the buffer's original raw data contained a zero, or it could overrun 1000 because there was never any zero value.

...thus you need to re-use the buffer-length, like so:

#define TEMP_LENGTH 1000

char temp[ TEMP_LENGTH ];

...

fgets( temp, TEMP_LENGTH, user_file );

Finally, you're making the same mistake when you call fgets( temp, ..., stdin ).

Comments