Page 1 of 1 [ 3 posts ] 

fgets
Butterfly
Butterfly

User avatar

Joined: 29 Sep 2014
Age: 35
Gender: Male
Posts: 13

06 Dec 2014, 11:23 pm

Fopen won't open in C successfully, and I'm on the linux platform using the gcc compiler. It's the unconfigured C compiler on linux. What I would like to do is open a simple text file in read only mode, but the fopen function failed. Here's the source code:

Quote:
FILE *ifp = fopen("input.txt", "r");
fgets(buf, 1024, ifp);

if(ifp == NULL) {
fprintf(ifp, "can't fopen file: %s", buf);
}

fputs(buf, ifp);
fscanf(ifp, "%s", buf);
fprintf(ifp, "%s\n", buf);

fclose(ifp);
return EXIT_SUCCESS;



JitakuKeibiinB
Veteran
Veteran

User avatar

Joined: 28 Jul 2012
Age: 33
Gender: Male
Posts: 714

07 Dec 2014, 2:54 am

Are you sure you want to be using fputs and fprintf (or not a different file)? You're reading it and then writing it back to the same (read-only) file. Also, you should check if it's NULL /before/ using fgets (and handle it, because yours is going to print the error and then crash).



fgets
Butterfly
Butterfly

User avatar

Joined: 29 Sep 2014
Age: 35
Gender: Male
Posts: 13

15 Jan 2015, 3:30 am

Not sure. How do you read a text string with fopen?