xmitz xmitz - 1 month ago 16
C Question

C - Writing on second line of file

Im doing the Hangman game on C and I have a trouble on one of the txt files.
I'm trying to append "num_letters" on the second line of the file.My code prints on new line everytime I guess. Is there a "lightweight" way to skip the first line and append on the second one?

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

Answer

Here you go:

/* 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;
}

Hopefully it makes sense, I think this does not need any further explanation, since the code explains it itself. However, if you want to clarify something, feel free to ask.