xmitz xmitz - 1 month ago 6
C Question

C - Append on 2nd line of file

Im trying to append on the 2nd line of my txt file. The format I want for my txt file is the following:

1 2 3 4 5


1.2 3.5 6.4 1.2 6.5


Basicly, I want to append on the first two lines of the file.

void write_stats(int tries, int num_letters, int tries_sucess)
FILE *stats;
stats = fopen("C:\\Users\\rjmal\\Documents\\CLION PROJECTS\\JogoDaForca\\stats.txt", "a");
if(stats == NULL)
{
printf("can't open file\n");
exit(0);
}
fprintf(stats," %d\n",tries);
fprintf(stats," %f",(float)tries_sucess/num_letters);
fclose(stats);

}


How do I make that without making a new line on the file everytime I run my program?

With the code I made, I get something like:

1


3 1.5


1 2.3

Answer

Due to the way files and lines are considered in computers, you can not vertically print as you desire. Instead, what you can do is storing all these numbers (i.e. tries AND (float)tries_sucess/num_letters) in two arrays and printing the contents of each array on the same line in that order. In effect, this would be buffering your content before printing and formatting it as you desire.

In that way, you can print all the data into two lines, which now correspond to an array, each.

Alternatively, you can create two char arrays and consider them as actual string buffers and use sprintf to record into them. Then, once you're done, you can print each char array through a single fprintf call.

Assuming you created two sufficiently long char arrays, below is a sample code for new write_stats. It now only serves to record the stats into two buffers.

void write_stats(int tries, int num_letters, int tries_sucess, char* buffer1, char* buffer2)
{
    sprintf(buffer1 + strlen(buffer1)," %d\n",tries);
    sprintf(buffer2 + strlen(buffer2)," %f",(float)tries_sucess/num_letters);
}

Note that you need to initiate the buffers with 0 to be able to easily make use of strlen function as I did. Also, you will eventually (i.e. when you are done calling write_stats ) need to call fprintf, in a block that buffer1 and buffer2 are defined in, as follows.

FILE *stats;
stats = fopen("C:\\Users\\rjmal\\Documents\\CLION PROJECTS\\JogoDaForca\\stats.txt", "a");
if(stats == NULL)
{
    printf("can't open file\n");
    exit(0);
}
fprintf(stats,"%s\n%s", buffer1, buffer2);
fclose(stats);

Since there are quite a few details to keep in mind, I think it is best you see this idea at work. See here for a working implementation, with some comments to help elaborate some details. As you may observe, the output given there is horizontal and is in 2 lines, as you described and as given below.

1 3 13 55 233
2.000000 1.600000 1.619048 1.617978 1.618037