S
Steven Jones
I'm just learning c and have an io question (more "i" then "o"). I could not
find a relevant answer in the FAQ. The following code is supposed to demo
fputc, fgetc and fgets. I first open a file, write a line of text to it and
close it. Next I use two separate methods to read the text back in. The output
section works as expected (verified by opening the file in an editor).
Neither input test work however. fgetc returns EOF immedatly and buffer
remains empty after the call to fgets. What am I overlooking?
Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#define SIZE 80
char fname[] = "/home/sj/iotest";
char sourcetext[] = "Why ask why, try bud dry\n";
char buffer[SIZE+1];
main()
{
FILE *fptr;
printf("\nOpening %s for writing\n", fname);
fptr = fopen( fname, "w");
int i;
for(i=0; i<strlen(sourcetext); i++)
fputc( sourcetext, fptr);
close(fptr);
printf("\nRead text using fgetc\n");
fptr = fopen( fname, "r");
do{
i = fgetc( fptr);
printf("%c", (char)i);
}while( i != EOF);
close(fptr);
printf("\n\n");
printf("\nRead text using fgets\n");
fptr = fopen( fname ,"r");
fgets( buffer, SIZE, fptr);
close(fptr);
printf("buffer = %s", buffer);
printf("\n");
}
/* **** result
[sj@KUTI demo]$ ./a.out
Opening /home/sj/iotest for writing
Read text using fgetc
\377
Read text using fgets
buffer =
********* */
find a relevant answer in the FAQ. The following code is supposed to demo
fputc, fgetc and fgets. I first open a file, write a line of text to it and
close it. Next I use two separate methods to read the text back in. The output
section works as expected (verified by opening the file in an editor).
Neither input test work however. fgetc returns EOF immedatly and buffer
remains empty after the call to fgets. What am I overlooking?
Thanks in advance
#include <stdio.h>
#include <stdlib.h>
#define SIZE 80
char fname[] = "/home/sj/iotest";
char sourcetext[] = "Why ask why, try bud dry\n";
char buffer[SIZE+1];
main()
{
FILE *fptr;
printf("\nOpening %s for writing\n", fname);
fptr = fopen( fname, "w");
int i;
for(i=0; i<strlen(sourcetext); i++)
fputc( sourcetext, fptr);
close(fptr);
printf("\nRead text using fgetc\n");
fptr = fopen( fname, "r");
do{
i = fgetc( fptr);
printf("%c", (char)i);
}while( i != EOF);
close(fptr);
printf("\n\n");
printf("\nRead text using fgets\n");
fptr = fopen( fname ,"r");
fgets( buffer, SIZE, fptr);
close(fptr);
printf("buffer = %s", buffer);
printf("\n");
}
/* **** result
[sj@KUTI demo]$ ./a.out
Opening /home/sj/iotest for writing
Read text using fgetc
\377
Read text using fgets
buffer =
********* */