I try to read a temporary file consisting of several lines like the following example. The lines are NOT sorted.
3;NOK
2;OK
1;NA
For an easy output-function, in which I want to offer several possibilities of output (CSV, Print on Screen...), I thought it would be clever to do the following.
- Open the file
- Iterate through the lines
- Extract the number at the beginning
- Use this as index of an array
- The result should be a "sorted" array
A minimal example which gives me an Segmentation Fault.
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[]){
FILE *outfp = fopen("test.txt", "r");
if (outfp == NULL){
printf("There was a problem: Temporary output-file could not be opened");
return 1;
}
// OUTPUT HANDLING
char output_line[1024];
char output_cut[1024];
int line_number;
char *output_array[3]; //The maximum number of possible entries is fixed
// I got variables for the line, for the linenumber and output_cut is needed for sscanf
while(fgets(output_line, sizeof(output_line), outfp)!=NULL){
sscanf(output_line,"%d;%s",&line_number,output_cut);
output_array[line_number]=output_line;
}
printf("LINE1:%s",output_array[1]);
printf("LINE2:%s",output_array[2]);
printf("LINE3:%s",output_array[3]);
return 0;
}
My first question: Is this the right way to do, or are there other better ways to "sort" this kind of file in an easy way for flexible output?
If yes, why does this not work?
Regards
Markus
Edit: the example textfile just contains numbers from 1-3... not 13,14...
Edit2: the solution
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]){
FILE *outfp = fopen("test.txt", "r");
if (outfp == NULL){
printf("There was a problem: Temporary output-file could not be opened");
return 1;
}
// OUTPUT HANDLING
char output_line[1024];
char output_cut[1024];
int line_number;
char output_array[4][1024]; //The maximum number of possible entries is fixed
// I got variables for the line, for the linenumber and output_cut is needed for sscanf
while(fgets(output_line, sizeof(output_line), outfp)!=NULL){
sscanf(output_line,"%d;%s",&line_number,output_cut);
strcpy(output_array[line_number],output_line);
}
printf("LINE1: %s",output_array[1]);
printf("LINE2: %s",output_array[2]);
printf("LINE3: %s",output_array[3]);
return 0;
}