1

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();
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Michael Kross
  • 47
  • 1
  • 4

4 Answers4

2

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);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

No, there is no portable/standard way of doing what you want.

Files are random access, but you can't insert data into a file since that would force all the other data to move, which is not an operation supported by typical file systems.

The best solution is to do it in two steps:

  1. Read through the input, while writing output to a new file
  2. Rename the new file to replace the original input
unwind
  • 391,730
  • 64
  • 469
  • 606
1

While the answers are correct and you can't add a string in the beginning of a file in C (using only FILE commands), you can interact with the operating system and use bash command 'sed' (in Linux) that solve the problem pretty easily without creating a new file and copy the content of the older file.

void AddTextToFirstLine(const char* file_name, const char* text)
{
char command_string[100]; //Preferably some constant but can be done with malloc of size strlen(text) + strlen(file_name) + 16 (chars in the command + nullbyte)
sprintf(command_string, "sed -i '1 i\\%s' %s", text, file_name);
system(command_string); //executing the sed command
}

You can also look for the equivalent of 'sed' in Unix system for Windows: Is there any sed like utility for cmd.exe?

Although calling the operating system is not recommended usually (because every operating system action stops the program flow and therefore damage time efficiency) This is one of the rare cases in which its ok since we're calling the operating system anyway when we're creating a file (or a copy file in that case). Therefore using this method will also decrease the running time compare to the solution of creating a copy file and copy the content of the old file to it.

0

Adding string in the beginning of file is just like inserting.
And you can't really directly insert string using C, instead you will overwrite old content.
So you can only do an overhaul to the text file: record old file content somewhere(temp file or memory...etc), write your string, then paste old content back.

moeCake
  • 512
  • 4
  • 15