我正在使用C进行Hangman游戏,我在其中一个txt文件上遇到了麻烦。 我正试图在文件的第二行附加“num_letters”。我想每次都会在新行上打印代码。是否有“轻量级”方式跳过第一行并附加到第二行?
void write_stats(int tries, int num_letters)
{
FILE *stats;
stats = fopen("C:\\Users\\rjmal\\Documents\\CLION PROJECTS\\JogoDaForca\\stats.txt", "a");
fprintf(stats," %d",tries);
fprintf(stats,"\n %d",num_letters);
fclose(stats);
}
答案 0 :(得分:0)
你走了:
/* Compiles with: gcc main.c -o test -pedantic -Wall -Wextra */
#include <stdio.h>
int write_stats(const int tries, const int num_letters, FILE* file) {
if (!file)
return -1;
const int written = fprintf(file, "%d\n%d", tries, num_letters);
if (written < 0)
return -1;
return 0;
}
int read_stats(int* tries, int* num_letters, FILE* file) {
if (!file)
return -1;
if (fscanf(file, "%d\n%d", tries, num_letters) != 2)
return -1;
return 0;
}
int main() {
/* writing stats */
FILE* w_stats = fopen("stats.dat", "w");
if (!w_stats) {
fprintf(stderr, "Could not open the file specified!\n");
return 1;
}
if (write_stats(3, 8, w_stats) != 0) {
fprintf(stderr, "Problem occoured while writing stats!\n");
fclose(w_stats);
return 1;
}
fclose(w_stats);
/* reading the stats */
FILE* r_stats = fopen("stats.dat", "r");
if (!r_stats) {
fprintf(stderr, "Could not open the file specified!\n");
return 1;
}
int tries, num_letters;
if (read_stats(&tries, &num_letters, r_stats) != 0) {
fprintf(stderr, "Problem occoured while reading stats!\n");
fclose(r_stats);
return 1;
}
fclose(r_stats);
printf("tries: %d, num_letters: %d\n", tries, num_letters);
return 0;
}
希望它有意义,我认为这不需要任何进一步的解释,因为代码本身就解释了它。但是,如果你想澄清一些事情,请随时提出。