Click to See Complete Forum and Search --> : read and write to file
trasher
May 7th, 2003, 12:04 PM
I want to read things from a file, and then, overwrite it later a the same line. Is there an easy way to go to the same location it was before to overwrite the information ? (getting a line number or something like that)
thanks for any suggestions
kenrus
May 7th, 2003, 12:19 PM
look into the function - lseek() and/or fseek()
Sincerely,
Kendall Russell
Zarimax
May 7th, 2003, 12:56 PM
You can use fseek to reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file. fseek clears the end-of-file indicator and negates the effect of any prior ungetc calls against stream.
When a file is opened for appending data, the current file position is determined by the last I/O operation, not by where the next write would occur. If no I/O operation has yet occurred on a file opened for appending, the file position is the start of the file.
For streams opened in text mode, fseek has limited use, because carriage return–linefeed translations can cause fseek to produce unexpected results.
fseek can be used to point to any part of a file.. The problem I'm having is overwritting text that is already there..
This is what MSDN has to say about fopen:
When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.
So how do I get past that limitation? There are 41 characters of text at the end of a file that I need to overwrite.
trasher
May 7th, 2003, 01:03 PM
exactly, I really need to overwrite some text at specific location of a file.
I read into the file. Then, I need to go back to insert new text a certains lines....
Zarimax
May 7th, 2003, 01:20 PM
exactly, I really need to overwrite some text at specific location of a file.
I'm having the same problem. Right now I'm looking to see if the solution is in this thread:
http://www.codeguru.com/forum/showthread.php?threadid=243570
kenrus
May 7th, 2003, 02:16 PM
I have an application that does this very thing.
It has an input file, it sorts the input file, as it is processing the input file it writes the records to an output file in the original non-sorted order.
These are the functions that we use to open, seek and write the data.
--Begin Code Snippet--
FILE *out_fh = 0;
long offset = 0;
int record_len = 601;
char achRec[602] = {0};
out_fh = fopen("myfile.txt", "wb")
<--code that figures out where offset should be-->
<--code that figures out what achRec should be-->
fseek(out_fh, offset, SEEK_SET)
fwrite(achRec, record_len, 1, out_fh);
--End Code Snippet--
I hope this helps.
Sincerely,
Kendall Russell
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.