EmadSmart
EmadSmart

Reputation: 81

How to write strings in different places of a file in C

in the code below:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
    FILE *fp ;
    fp = fopen("out.txt", "r+");
    int count = 1;
    char ch ;
    char userInput[5] ;
    int lineNumber = 0;
    while (lineNumber!= -1){
        fgets(userInput, sizeof(userInput), stdin);
        lineNumber = atoi(userInput);
        while((ch=fgetc(fp))!=EOF)
        {
            if(ch=='\n')  //counts number of lines
                count++;
            if(count == lineNumber)
            {
                fprintf(fp, "writed %d\n", count);
                fseek(fp, 0, SEEK_SET);
            }

        }
    }
    return 0;
}

I want to write a string in the line which the user gives me,i store the user answer in userInputand then convert it to the int and store it in lineNumber. when i try to write fore example in line 90 (my file has 100 lines) two error i get: 1.the file reduce to a 91-line file (instate of remain 100 lines) 2.although i seek to first of file,no more lines written in the next loops and user inputs.

Upvotes: 1

Views: 100

Answers (1)

Steve Summit
Steve Summit

Reputation: 47952

Reading a file (to count its lines) and then turning around and writing to it is tricky. Among other things, you have to do something like an fseek between the reading and the writing. So try interchanging the order of the fseek and fprintf calls:

fseek(fp, 0, SEEK_SET);
fprintf(fp, "writed %d\n", count);

Also, be aware that unless the new text you're writing ("writed ###") is exactly the same length as whatever line used to be there, the line structure of the remainder of the file is likely to get garbled.

See also this question in the C FAQ list.

Upvotes: 1

Related Questions