[Solved] How can i create a file .csv?


If you want to write the results in a file, move

FILE *f = fopen("test", "w");

into your main() function (also check return value since the function can fail), if you want the file format to be csv then you should add the extension .csv so that other people know it has that format e.g. “test.csv” instead of “test”. pass the file pointer to all the functions where you need to write to the csv-file.

Now to serialize the contents that you have collected and since the format of a csv-file is row based you need to collect the information before you write it (easier that way). So decide on a structure that will contain all the information you want to put in a row in the csv-file and fill that structure, have a linked list of these structures that you create as you are gathering information, then once you are done collecting, go through the list and write one row to the csv-file per structure.

E.g.

typedef struct CsvRow
{
  char ipLocal[32];
  char ipRemote[32];
  ...
  struct csvRow* next;
} Csvrow;

CsvRow* first;
CsvRow* last;

// collecting
CsvRow* newLine =  malloc(sizeof(CsvRow));
newLine->next = NULL;

if (last == NULL) 
{
  first = last = newLine;
}
else
{
  last->next = newLine;
  last = newLine;
}

// then when you are gathering information just add that in last

strcpy(last->ipLocal, "someip");
..

// at the end of your main function do

FILE* fp = fopen("test.csv", "w");
if (fp == NULL)
{
  fprintf(stderr, "file access denied");
  abort();
}
for (CsvRow* p = first; p != NULL; p = p->next)
{
  fprintf(fp, "%s,%s\n", p->ipLocal, p->ipRemote);
}
fclose(fp);

// free memory
CsvRow* q = first;
while (q != NULL)
{
   CsvRow* next = q->next; 
   free(q);
   q = next;
}

3

solved How can i create a file .csv?