tags:

views:

163

answers:

6

What ever could be the problem with it?

#include <stdio.h>
#include <string.h>
#define SIZE 19

void filePrint(char fileName[]);

int main (void)
{
   char fileRead[SIZE];

   filePrint(fileRead);

   return 0;
}

void filePrint(char fileName[])
{
   FILE *inp;
   int input_status = 0;
   char readFile[SIZE];

   inp = fopen(fileName, "r");

   printf("\nEnter a file to print:\n");

   input_status = fscanf(inp, "%s", readFile);

   while (input_status != EOF)  
   {
      printf("%s\n", readFile);
      input_status = fscanf(inp, "%s", readFile);
   }

   fclose(inp);
}
+3  A: 

Among other things, you never actually specify the file to read from?

Amber
Actually, the segfault happens when he tries to read from the filehandle, which is dereferencing a `NULL` pointer. But the pointer is `NULL` for the reason you state, so +1 for being helpful instead of pedantic.
Chris Lutz
If `fileRead` doesn't happen to contain any NUL characters, the segfault may happen before `fopen()` returns.
bk1e
+1  A: 

Looks like you never put anything into fileRead[] in main, before you fed it to filePrint(), which gave it to fopen(). I.e., "uninitialized data"

JustJeff
+6  A: 

I think you should go back and read a chapter on File I/O.

Run through the code you wrote in your mind, and out loud.

You're trying to open a file, stored in the fileName string, but the string hasn't been initialized to anything that is valid (for fopen). fopen returns a NULL pointer if it cannot open a file. You cannot use this NULL pointer to read from. Also, if you're using fscanf to read from the file you just opened, a user cannot type anything.

Nick Presta
+2  A: 

When you call fopen(fileName, "r");, fileName has not been filled with a filename. It's an uninitialized array.

Andrew Medico
thanks...i figured it out
Tomi
isn't this the right answer then?
Craig
+1  A: 

Hi,

If you mentioned the filename in fileRead[] array also,you will get the segmentation fault. Because you specified the array size is 19.You should specify the large array size in fileRead[] array like 1024.

rekha_sri
+1  A: 

You should give the filename for the function.

You pass the character array without value. So that time, the value of the array is null. In the fopen function you are tried to open the file.

So the fopen function return null value. If the fopen function open the file successfully it will return the correct file pointer. Else it will return the null, The error will be stored in the errno.

Using the null pointer you can't read.

muruga