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();
}