So you want to change all bytes in the file to the letter g
. Doing this on a text stream portably and reliably is surprisingly difficult1. I suggest you open the stream in binary mode instead and do something like this:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[4096];
long len;
FILE *fp;
fp = fopen("temp.txt", "rb+");
if (fp == NULL) {
fprintf(stderr, "cannot open temp.txt: %s\n", strerror(errno));
return 1;
}
while ((len = fread(buf, 1, sizeof buf, fp)) > 0) {
fseek(fp, -len, SEEK_CUR);
memset(buf, 'g', len);
fwrite(buf, 1, len, fp);
fseek(fp, 0, SEEK_CUR);
}
fclose(fp);
return 0;
}
Your question is not completely clear: if by update all the characters to 'g' you mean to leave unchanged bytes that are not characters, such as newline markers, the code will be a bit more subtile. It is much simpler to write a filter that reads a stream and produces an output stream with the changes:
For example, here is a filter that changes all letters to g
:
#include <ctype.h>
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (isalpha(c))
c = 'g';
putchar(c);
}
return 0;
}
- One cannot use
ftell()
in text mode to compute the number of characters in the file. You must use binary mode:
C 7.21.9.4 the ftell
function
Synopsis
#include <stdio.h>
long int ftell(FILE *stream);
Description
The ftell
function obtains the current value of the file position indicator for the stream pointed to by stream
. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek
function for returning the file position indicator for the stream to its position at the time of the ftell
call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
Returns
If successful, the ftell
function returns the current value of the file position indicator for the stream. On failure, the ftell
function returns −1L
and stores an implementation-defined positive value in errno
.
Even counting characters read with getc()
and writing the same number of 'g'
s from the beginning of the file does not work: the newline sequences may use more than one byte and some of the file contents at the end may not be overwritten on some legacy systems.