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.
Running the program as is will get output like this:
#define MAX 200
int num = 1;
FILE * fp;
if ((fp = fopen("wordy.txt", "a+")) == NULL)
fprintf(stdin, "Can't open \"wordy.txt\" file.\n");
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')
fprintf(fp, "%s ", words);
while (fscanf(fp, "%s", words) == 1)
printf("%d ", num); // these two lines were all I had
num++; // to add to complete the exercise
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file.\n");
Running it again, with new input will append like this:
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.