Search code examples
cfwrite

fwrite() appends instead of write C


I have to write a program witch reads from a file received by line and then it overwrites it with the read words uppercased. This is my code

void toUpperCase(char* string) {
int i=0;
while(string[i])
{
    string[i]=toupper(string[i]);
    i++;
} }
int main(int argc, char** argv) {
if(argc==1)
{
    puts("Error: INSERT PATH");
    exit(0);
}
char* file=argv[1];
FILE* fd=fopen(file,"r+");
if(fd<0)
{
    perror("Error opening file: ");
    exit(0);
}
char buffer[30][30];
int i=0;
while(!feof(fd))
{
    fscanf(fd,"%s",buffer[i]);
    i++;
}
int j=0;
for(j=0; j<i; j++)
{
    toUpperCase(buffer[j]);
    fwrite(buffer[j],strlen(buffer[j]),1,fd);
}
fclose(fd);
return 0; }

but this program appends the words contained in buffer[][] instead of overwriting the file. If the file contain was something like pippo pluto foo then, after the execution is pippo pluto fooPIPPOPLUTOFOO instead of PIPPO PLUTO FOO. Where am i wrong? Thank you


Solution

  • You have to reset the file position indicator using fseek, as fscanf will advance it. Something like

    fseek(fd, length_of_read_string, SEEK_CUR);
    

    This allows you to read the file in chunks, but it will be tricky to get right. Or of course reset it to the file start because you read everything in 1 go:

    fseek(fd, 0L, SEEK_SET);
    

    I strongly recommend writing the modified data into a new file, and then after the program has run, delete the initial file and rename the new one. That will also take care of another issue with your program, you are reading the entire file into memory before handling it.