BTW:
Code:
fseek(fptr, 0, SEEK_SET);
That's the same as
Code:
getchar();
getchar();
getchar();
The more, the merrier!
Why not just use something like this?
Code:
while(getchar() != '\n');
2. getc returns int 0-255 values are for byte read from file and -1 (EOF0 is used to indicate end-of-file event
so in general usage of this function should be
Code:
int letter;
letter = fgetc(fp);
if(letter != EOF)
{
unsigned char readLetter = (unsigned char)letter;
/* use readLetter */
}
Not necessarily. Most of the time, you can probably just read the letter as an int and keep it as an int. (chars are automatically promoted to ints when they're passed to varargs functions like printf() anyway, and with prototyped functions the compiler should be able to handle things.)
Anyway -- it's strange that your code isn't working, because this overwrites the '5' correctly for me.
Code:
#include <stdio.h>
#define FILENAME "overwrite.txt"
int main() {
int c;
FILE *fp = fopen(FILENAME, "w");
fputs("1234567890", fp);
fclose(fp);
fp = fopen(FILENAME, "r+");
fseek(fp, 5-1, SEEK_SET); /* overwrite the '5' */
putc('*', fp);
rewind(fp);
while((c = getc(fp)) != EOF) putchar(c);
getchar();
return 0;
}
The only thing that I can think of is that rewind() flushes the file and fseek() does not -- because you need to flush the file (such as with fflush()) as you switch between reading and writing.
Again, though, I agree with citizen -- why not just read in a line, change that, and re-create the file? It's probably more efficient, actually -- less file manipulation.