Shweta
Shweta

Reputation: 5456

fputs creating a problem

fseek(ofile, 13, SEEK_SET);
fputs("\t", ofile);

do
{
     ch = getc(ofile);
     printf("%c", ch);

     if(ch == '\n') {
         fseek(ofile, 13, SEEK_CUR);
         fputs("\t", ofile);
     }
} while(ch != EOF);

I have written this program which manipulates a file and inserts a \t after a particular position in each line. Whenever I use second fputs it makes file unreadable. Why is this happening?

Upvotes: 0

Views: 1400

Answers (1)

paxdiablo
paxdiablo

Reputation: 882326

A few things you may want to look at:

  • fputs doesn't insert anything, it overwrites whatever was there. In other words, that TAB character will simply overwrite whatever was originally there. If you want to insert things, you're better off writing a filter-type program which copies characters from one file to another, allowing changes along the way (like inserting if the last newline was 13 characters ago, for example).
  • Your fseek will change the current position for both writing and subsequent getc operations. That means you need to watch out for lines shorter than you expect.
  • You really should check the return values from fseek and fputs - it is possible that they may fail.
  • After a getc, the file pointer is at the next character, so make sure it's the one fourteen characters after the newline that you're interested in.
  • Watch out for the final newline in the file. It's unlikely that the seek 13 bytes beyond that will work and you're doing an fputs anyway.

Failing all that, dump out the modified file in hex mode with something like the Linuxy:

od -xcb myFileName.txt

and see what the individual bytes are. gEdit is notorious for rejecting files which even have one character out of whack, which is why I use vim for everything :-)

Upvotes: 4

Related Questions