0

I am trying to swap the existing characters from the file with new characters one by one. The new characters are obtained by manipulating the existing characters by subtracting one from the ASCII code. The file already exists with text, but I ended up getting an infinite loop for some reason. What am I doing wrong?

#include <stdio.h>

int main()
{
  FILE *fp = fopen("myfile.txt", "r+");

  if (fp == NULL)
    printf("File cannot be opened.");
  else
  {
    // Used for retrieving a character from file
    int c;

   // Pointer will automatically be incremented by one after executing fgetc function
    while ((c = fgetc(fp)) != EOF)
    {
        // Decrement pointer by one to overwrite existing character
        fseek(fp, ftell(fp)-1, SEEK_SET);

        // Pointer should automatically increment by one after executing fputc function
        fputc(c-1, fp);

        printf("%c\n", c);
    }

    fclose(fp);
 }

    return 0;
}

-EDIT- I changed datatype of c from char to int, but problem still persisted. However, my problem has been resolved by adding fseek(fp, 0, SEEK_CUR) after fputc() call. I believe Jonathan Leffler's comment should become an answer since this kind of problem was not answered from the other question.

Gizdich
  • 1
  • 4
  • 1
    [The `fgetc` function](http://en.cppreference.com/w/c/io/fgetc) returns an `int`. There is a reason for it. I recommend you change your variable `c` accordingly. – Some programmer dude Oct 01 '16 at 20:21
  • 2
    You have to position both when you change from reading to writing and when you change from writing to reading. Add `fseek(fp, 0, SEEK_CUR)` after the `fputc()` call. (Why? The standard says so! See `fopen()` describing `+` modes: _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._ – Jonathan Leffler Oct 01 '16 at 20:27
  • Whoops, I forgot that fgetc returns an int. I changed the data type of c to int, but the problem persisted. However, adding fseek(fp, 0, SEEK_CUR) after fputc() call actually solved my problem. Thank you! – Gizdich Oct 01 '16 at 20:55

1 Answers1

0

try this

#include <stdio.h>

int main(void){
    FILE *fp = fopen("myfile.txt", "r+");

    if (fp == NULL) {
        printf("File cannot be opened.");
        return -1;
    }

    int c;
    long pos = ftell(fp);
    while ((c = fgetc(fp)) != EOF){
        fseek(fp, pos, SEEK_SET);//In the case of text file Do not operate the offset.
        fputc(c-1, fp);
        fflush(fp);//To save the output.
        pos = ftell(fp);

        printf("%c\n", c);
    }
    fclose(fp);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70