Mail Archives: djgpp/1998/09/08/06:33:31
On Mon, 7 Sep 1998, Larry Ochoa wrote:
You can't read from and write to a file simultaeneously. Each time you
write to the file the file pointer is positioned directly after the last
byte you wrote. When you call the fgets function you are scanning in
rubbish, and messing up the file pointer for the next write.
Write all the data to the file first, close the file properly or
reposition the file pointer at the beginning of the file with fseek [
fseek(file,0,SEEK_SET) ], and then read all your data back in again.
> Hi,
> When I try to compile the following program:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> main(void)
> {
> FILE *file;
> char name[]= "file.txt";
> char blah[5];
> enum {success, fail};
> int i, f_s = success;
>
> if ((file = fopen(name, "w+")) == NULL) {
> printf("Cannot open %s.\n", name);
> f_s = fail;
> } else {
> for(i=1;i<=100;i++) {
> fprintf(file,"%d\n",i);
> fgets(blah, 5, file);
> printf("%s\n", blah);
> }
> }
> fclose(file);
> return f_s;
> }
>
>
> with djgpp, something happens to "file.txt". Instead of just putting the
> number like this:
>
> 1
> 2
> 3
> 4
>
> I get this(file is attached):
>
> 1
> ¼ €2
> „± 3
> h`< 4
>
Elliott Oti
http://www.fys.ruu.nl/~oti
"Q: What did the elephant say to the naked man?
A: It's cute but can you pick up peanuts with it?"
- Raw text -