Question

this is what i'm trying to do,

I have a file with information in it. I'm trying to rewrite it so before every line, the number of the line will appear.

The basic idea i have in mind works like this:

while i haven't reached the end of the file:
save the first line of the file (100 characters or until null is reached) in str
go back to the file, and write "line number" and then the info in str.
now str takes the next 100 chars...rinse and repeat.

Actual code:

void add_line_number(FILE* f1)
{
    char str[100];
    int i=1;
    fseek(f1,0,SEEK_SET);
    do
    {
        fgets(str,100,f1);
        fprintf(f1,"%d %s",i,str);
        i++;
        f1+=strlen(str);
    }while(strlen(str));
}

getting the error: Unhandled exception at 0x77e78dc9 in essay 4.exe: 0xC0000005: Access violation writing location 0xfffff204.

Was it helpful?

Solution

In general, you're not going to be able to get this to work in place. Adding a line number at the beginning of the line, then writing that back to the file, will cause the tail end of the first line to overwrite what was the beginning of the second line. You'll need to write the modified lines out to a separate file, then overwrite the original file after you're done. Alternatively, store all the lines of the file in memory, then overwrite the file in a second pass, but that'll be problematic for large files.

OTHER TIPS

I think the problem is in trying to increment the FILE* by strlen(str). Try it without that.

You're incrementing f1. That doesn't mean what you seem to think it means :)

Since you're inserting data into the file, you'll need to actually write to a different file, or do it all in memory and write to the file all at once. Also, you want to read to the end of the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top