3

Say I have a file pointer like this:

file_ptr = fopen(“test.txt”, “r+”);

and I want to change each char's ASCII value as I move through the stream (I am doing this as a cipher, so if there is a better or more efficient way to do this, please let me know).

I am trying to use a while(!feof(file_ptr)) {} loop with fgetc() and fputc, but the file_ptr will be pointing to the next char, so i want to know if there is something i can do point it backwards one spot.

Essentially, I want to know the file stream equivalent for:

char* blah="blah blah";
char* index=blah;
index++;/*how to navigate a file stream in this way*/
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
spatara
  • 893
  • 4
  • 15
  • 28

1 Answers1

10

Yes: you can use the fseek function:

fseek(file_ptr, -1L, SEEK_CUR); // move backwards one character

Furthermore, after your fputc and before your fgetc, you'll want to call fseek again:

fseek(file_ptr, 0L, SEEK_CUR); // don't move

just to notify the system that you're switching between reads and writes, so that it knows to properly flush all buffers and whatnot. (Otherwise you might not actually be where you think.)

By the way, for this to work properly, you'll want to open the file in binary mode rather than text mode:

file_ptr = fopen("test.txt", "rb+");

since otherwise the within-C definition of "character" might not exactly match the inside-the-file definition of "character" (especially when it comes to line endings), and fseek might put you in the middle of one of the latter.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Thanks! I wouldn't have known to notify the system like that...also, what is the purpose of the "L" in the offset parameter? – spatara Mar 03 '12 at 20:47
  • @spatara: No purpose, really. That just makes it a `long`, but if you write `-1`, the compiler will implicitly convert it to a `long` anyway (because it's being passed to a function that's declared as taking a `long`). Either one is 100% fine. – ruakh Mar 03 '12 at 20:52