inserting characters mid-stream?
The question mark in the title is because I'm not even sure if I'm on the right track. Anyway, here's something that's been torturing me all night with no relief...
I completed an exercise in my programming book where I was supposed to alter a program displayed in the chapter so besides just appending more words each time the program is run, it also displays sequential numbers for each new word, starting with the number 1.
The code below is my completed exercise, but then (apart from the book) I wondered if I could successfully accomplish the same goal again, but this time actually *write* the numerical values to the file (instead of just sending them to stdout).
Can anyone think of suggestions as to how I might accomplish this? I've spent hours fiddling with string functions, ctype functions, fseek, etc., with no joy at all.
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 200
int main(void)
{
int num = 1;
FILE * fp;
char words[MAX];
if ((fp = fopen("wordy.txt", "a+")) == NULL)
{
fprintf(stdin, "Can't open \"wordy.txt\" file.\n");
exit(EXIT_FAILURE);
}
puts("Enter words to add to the file; press the Enter");
puts("key at the beginning of a line to terminate.");
while (gets(words) != NULL && words[0] != '\0')
fprintf(fp, "%s ", words);
puts("File contents:");
rewind(fp);
while (fscanf(fp, "%s", words) == 1)
{
printf("%d ", num); // these two lines were all I had
num++; // to add to complete the exercise
puts(words);
}
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file.\n");
return 0;
}
Running the program as is will get output like this:
1 hello
2 my
3 name
4 is
5 freddie
Running it again, with new input will append like this:
1 hello
2 my
3 name
4 is
5 freddie
6 what
7 is
8 your
9 name?
In this scenario, after running the program these two times, if you open the file 'wordy.txt', you get (no numbers, of course):
hello my name is freddie what is your name?
I would have just moved on to the next exercise, but I'm thinking that being able to insert data anywhere in a file is probably an important thing to know.
Thank you in advance for any helpful ideas.