Search code examples
cstringtextfile-iofopen

C programming; adding strings to beginning of line in file


I'm trying to add numbering to several lines of text in an existing .txt file using fopen's "r+" mode. This doesnt' seem to work and it ends up writing the first iteration of the string "line" followed by a large amount of junk value. Is there any way to add text at the beginning of a line? If so, am i coming at this the wrong way?

Also im trying to do this without having to write up a whole new file.

void main()
{
    char read = ' ';
    char buffer[25];
    char line[4] = "01."; //lines from 01 to 99
    FILE *file;
    file = fopen("readme.txt","r+");
    if (file == NULL)
    {
        printf("ERROR: Cannot open input file.\n");
        exit();
    }
    do
    {
        fwrite(line,strlen(line),1,file);
        read=gets(buffer);
        if(!feof(file)) // updating line numbers
        {
            if(line[1]<'9')
            {
                (line[1])++;
            }
            else
            {
                if(line[0]<'9')
                {
                    (line[0])++;
                }
                else
                {
                    exit();
                }
            }
        }
        else
        {
            exit();
        }
    }while(!(feof(file)));
    fclose(file);
    exit();
}

Solution

  • Files in C let you overwrite and append, but not "prepend" data. To insert at the beginning or in the middle, you must copy the "tail" manually.

    If you are writing a line-numbering program, it would be much simpler (and faster) to write the result into a separate temporary file, and then copy it in place of the original once the operation is complete.

    You can use a simple loop that reads the original file line-by-line, and writes the output file, for example, with fprintf:

    fprintf(outFile, "%02d.%s", lineNumber++, lineFromOrigFile);