Question

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.

  1. Open the file
  2. Iterate through the lines
  3. Extract the number at the beginning
  4. Use this as index of an array
  5. 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;
}
Was it helpful?

Solution

You have two major problems with the code as shown in the question. The first is that all the pointers in the output_array points to the same place. This means that when you print the lines all will print the same (which will be the last line read).

The second problem is your array indexing. Array indices goes from zero to the size minus one, so for your output_array the indices are 0 to 2 (inclusive). The problem causing the crash is that you use index 3 which is out of bound for the array, and leads to undefined behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top