Home > other >  reading data from a file after skiping the header
reading data from a file after skiping the header

Time:12-30

I'm trying to read numbers from a file, but first i gotta skip a header, this is a small code that only serves the purpose of testing the function, now...the function to skip part of the file works fine but when i try and read somthing from the file after i get a seg fault and the error code that means Status_acces_violation, but i just can't seem to find my mistake The info in the file is always gonne be like this Ex:

P5

256 789

125

125 236 789 ...(a bunch of numbers)

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *salt_header(FILE *poza){

   char gunoi1[2];
   fscanf(poza, "%s", gunoi1);
   printf("%s\n", gunoi1);

   int gunoi2;
   fscanf(poza, "%d ", &gunoi2);
   printf("%d ", gunoi2);

   fscanf(poza, "%d", &gunoi2);
   printf("%d\n", gunoi2);

   fscanf(poza, "%d", &gunoi2);
   printf("%d\n", gunoi2);

   return poza;
}

int main()
{    
   FILE *poza;
   char gunoi1[2], *nume;
   nume = malloc(256 * sizeof(char *));
   if(nume == NULL)
      exit(-11);

   scanf("%s", nume);
   poza = fopen(nume, "r");

   if(poza == NULL){
      printf("Failed to open file\n");
      exit(-1);
   }

   poza = salt_header(poza);

   int numar;
   for(int i = 0; i < 3; i  ){
      fscanf(poza, "%d", &numar);
      printf("%d ", numar);
   }

   fclose(poza);
   free(nume);
   return 0;
}

CodePudding user response:

char gunoi1[5]; // "P5" : 2 bytes , "\n" : 1 byte , "\0" : byte

CodePudding user response:

just can't seem to find my mistake

In *scanf(), do not use "%s" without a width.

fscanf(poza, "%s", gunoi1); overflows char gunoi1[2]; as it is too small to store string "P5" leading to undefined behavior (UB).

Also always check the return value of input functions.

  • Related