Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Reading from and writing to a file in C

Name: Anonymous 2012-03-08 17:18

If I want to read from and write to a file (in order to, say, write a spellchecker that automatically corrects any mistakes it detects)can I open it twice with two separate pointers, once in read mode and once in append mode? If not, what is the proper way to modify a file while reading it?

I apologize for the neophyte question.

Name: Anonymous 2012-03-08 17:20

copy the file to a temporary location and use it for reading.  Linux use /tmp/whatev, Windows... lol.

Name: Anonymous 2012-03-08 17:25

Cool. Thanks.

Name: Anonymous 2012-03-08 17:38

Use a Trie for a spellchecker.

Name: Anonymous 2012-03-08 17:46

FILE *f = fopen(filename, "a+");
fpos_t beginning, end;
fgetpos(f, &end); /* use this for writing */
rewind(f);
fgetpos(f, &beginning); /* use this for reading */

Since you said "append mode" you can do this and jump between positions with fgetpos and fsetpos. If you want to modify the file "in place" in Standard C you'd either have to read the original file into memory and reopen it for writing or write to a temporary file and then rename() it to the same name as the original after deleting the original.

Name: Anonymous 2012-03-08 17:51

Modifying it in place was what I had in mind, yes. Now I realize my error regarding the function of append.

Thank you for the comprehensive answer.

Name: Anonymous 2012-03-08 18:36

This isn't how you do rapid string lookups though.

Name: Anonymous 2012-03-08 20:51

fopen("shitdick.txt", "r+")

Don't change these.
Name: Email:
Entire Thread Thread List