Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Read and replace char

Tags:

c

I'm trying to read a file and replace every char by it's corresponding char up one in ASCII table. It opens the file properly but keep on reading the first character.

int main(int argc, char * argv[])
{
    FILE *input;
    input = fopen(argv[2], "r+");
    if (!input)
    {
        fprintf(stderr, "Unable to open file %s", argv[2]);
        return -1;
    }

    char ch;
    fpos_t * pos;
    while( (ch = fgetc(input)) != EOF)
    {
            printf("%c\n",ch);
            fgetpos (input, pos);
            fsetpos(input, pos-1);
            fputc(ch+1, input);
    }
    fclose(input);
    return 1;
}

the text file is

abc
def
ghi

I'm pretty sure it's due to the fgetpos and fsetpos but if I remove it then it will add the character at the end of the file and the next fgetc will returns EOF and exit.

like image 478
Danson Avatar asked Jun 23 '26 13:06

Danson


1 Answers

You have to be careful when dealing with files opened in update mode.

C11 (n1570), § 7.21.5.3 The fopen function

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream.

However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

So your reading might look something like :

int c;

while ((c = getc(input)) != EOF)
{
    fsetpos(/* ... */);
    putc(c + 1, input);
    fflush(input);
}

By the way, you will have problems with 'z' character.

like image 61
md5 Avatar answered Jun 27 '26 14:06

md5