In my code I have a file named "f1.txt" and the text inside this file is a string "robin singh hero"
I have created a string [b]str[/b] of size [10] and a FILE type pointer variable *fp then assigned this pointer the address of the my file "f1.txt" from the fopen function.
Then I used fgets function which takes these three parameters (string,size,file pointer)
#include <stdio.h>
void main()
{
char str[10];
FILE *fp;
fp = fopen("f1.txt","r");
if(fp == NULL)
{
printf("File does not exists");
exit(1);
}
while (fgets(str,8,fp)!=NULL){
printf("%s",str);
}
printf("\n");
fclose(fp);
puts(str);
puts(str);
}
I mentioned size 8 so it means fgets will read first eight characters (robin sin) from my file and store it to my string which is of size 10 and still 2 bytes of space in left in my string. then until my file reached a null it copies the next 8 characters (gh hero).
So I want to know this: 1. there are now 6 characters left, But the actual result is (robin singh hero)
What is happening here in the second step when there are only 6 characters left.
I wanted to know what's happened to my string str after the end of this while loop. so I did puts(str) and I am getting this value (ro) in the terminal.
Below is the actual result of this code: robin singh hero
ro
ro
printf("File does not exists");
This is not (necessarily) true. Suggest:perror( "fopen failed" )
as this will output both your error message and the text reason the system thinks the error occurred tostderr
– user3629249