Miribra Stacker
Miribra Stacker

Reputation: 23

get input from the file in C

i am new in programming and in stackoverflow that is why i sometime maybe can have simple questions when i code something and want to get input fromthe file`

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

int main(int argc, char *argv[])
{
   int len1=0;
   FILE* p;
   char a;
   char b[10];
   p = fopen(argv[1],"r");
   while (1)
   {
      a = fgetc(p);

      if(a == ' ') break;
      else
      {
         len1++; 
         b[len1-1] = a;
      }
   }
   printf("%c\n", b0);
   return 0;
}

it gives segmentation fault and what is the reason?

Upvotes: 1

Views: 4102

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You have a buffer overrun. If you change your while loop to stop after reading ten characters, even if space has not been reached, you should do fine.

Additionally, you are passing a character at b[len1] into printf, and have it interpreted as a pointer. This will segfault no matter what.

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

int main(int argc, char *argv[])
{
   int len1=0;
   FILE* p;
   char a;
   char b[10+1]; // <<== need one more byte for the terminator
   if (argc != 2)
   {
      fprintf(stderr, "Need to supply a filename\n");
      return (-1);
   }
   p = fopen(argv[1],"r");
   if (p == NULL)
   {
      fprintf(stderr, "Cannot open file %s\n", argv[1]);
      return(-2);
   }
   while (len1 < 10) // <<== avoid buffer overruns
   {
      a = fgetc(p);

      if(a == ' ') break;
      else
      {
         len1++; 
         b[len1-1] = a;
      }
   }
   b[len1] = '\0'; // <<== Don't forget to zero-terminate
   printf("%s\n", b); // <<== Pass the buffer, not the last character from it
   return 0;
}

Upvotes: 2

Eight
Eight

Reputation: 4284

There are two logical bugs in your program ::
1.while(1) you are having an non-terminating loop, it will result into stackoverflow.
2. char b[10] here, b is a char array of size 10 i.e. b[0] to b[9], but as in your program len1++ is executing for every iteration, which will access memory beyond b[9].

To overcome these issues use while(len1<10).

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 59987

You have two problems

  1. What happens when you read the file and the first 10 characters are not a space? The array b will be esxhausted.
  2. printf is trying to print a string. b[len1] is a character.

Upvotes: 0

TridenT
TridenT

Reputation: 4909

Instead of the while (1), you should test the loop index against the size of your table b (so 10)

What do you want to do exactly ?

Upvotes: 0

Doug T.
Doug T.

Reputation: 65589

char b[10] only has 10 elements. len1 is incremented every iteration of an infinite loop. This quickly becomes > 10. Eventually somewhere past 10 you write into some memory you don't have access too. Hence the seg fault.

Upvotes: 0

Related Questions