Search code examples
cincrement

How to give incremented numbers when printing data in file?


In this code, I am having a problem but don't know how to solve it. I need to print the result in file with incremented numbers. I used line++ but it'll only work in the loop and I want that if someone printed something then printing again should require the line number to increment.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 200

int main(){
  FILE * fp1 = fopen("file.csv", "a");
  char string[STRING_LEN];
  int line = 1;

  printf("Enter the string: ");
  fgets(string, sizeof(string), stdin);

  fprintf(fp1, "%d,%s\n", line++, string);

  return 0;
}

Solution

  • Looks like you need something like that:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define STRING_LEN 200
    
    int main(){
      char string[STRING_LEN];
      int line;
      FILE * fp1 = fopen("file.csv", "a+r");
    
      fscanf(fp1, "%d,%s\n", &line, string);
      printf("Enter the string: ");
      fgets(string, sizeof(string), stdin);
      fprintf(fp1, "%d,%s", ++line, string);
      
      fclose(fp1);
      return 0;
    }
    

    First, we read line from file, parse it and get line value, then write back incremented value. And do not forget to close file.