Description
I am trying to write a csv table, tablepath
, and I need to include in it the name of the variables, which are in a text file, filepath
. I am using a first function, read_par
, to retrieve the names from filepath
and a second function, store
, to write in the table.
Problem
The table created is systematically missing the name of the first variable from the text file. The read_par
function is functional and produces the expected output: a string containing the name of the variable, I also included it for context.
filepath
- Here is the structure of the text file:
par1
0 1 0.5
par2
1 1 1
par3
0 1 1
par4
0 1 1
par5
0 1 1
par6
0 1 1
store
Here is the
store
function:int store(int par_num, float sim_num, float **tab_param, char *filepath, char *tablepath){ int j; char *name = NULL; FILE* sim_table = NULL; sim_table = fopen(tablepath, "w"); // Start the first line in the table fprintf(sim_table,"simulation_number"); for(j=1; j < par_num+1; j++){ // If it is the last parameter -> create a new line if(j == par_num){ name = read_name(j, filepath); fprintf(sim_table,",%s\n", name); }else{ /* If it is not the last parameter -> continue writing on * the same line */ name = read_name(j, filepath); fprintf(sim_table,",%s", name); } } fclose(sim_table); return 0; }
read_name
Here is the
read_name
function:char *strtok(char *line, char *eof); char *read_name(int par_id, char *filepath){ char *par_name; int count = 0; FILE *file = fopen(filepath, "r"); if ( file != NULL ){ char line[256]; /* or other suitable maximum line size */ while (fgets(line, sizeof line, file) != NULL){ /* read a line */ if (count == (2*par_id)-2){ // strtok removes the \n character from the string line strtok(line, "\n"); par_name = line; fclose(file); } else{ count++; } } } else { printf("\n\n ERROR IN FUNCTION READ_PAR\n\nTEXT FILE IS EMPTY\n\n"); } return par_name; }
tablepath
The table I am obtaining looks like this:
┌─────────────────┬┬────┬────┬────┬────┬────┐
│simulation_number││par2│par3│par4│par5│par6│
└─────────────────┴┴────┴────┴────┴────┴────┘
With the par1
name missing, but all the other variable name successfully printed. I do not know where is the problem. Is it a problem in the for loop conditions or something to do with the par1
string itself?
Thanks for any help on this.