yetanotherstacker
yetanotherstacker

Reputation: 295

Segmentation fault while reading file

My file looks like:

123456789

My code gives me segmentation fault:

#include <stdio.h>

int main(){

    FILE *f; 
    char ch[5];
    f = open("a.txt", "r");
    fgets( ch, 4, f); 
    ch[4] = NULL;
    printf("%s", ch); //Fixed
    return 0;
}

I am an absolute beginner. What am I doing wrong. My aim is to read first 4 characters of the file using fgets.

Upvotes: 2

Views: 4737

Answers (4)

Hemant Metalia
Hemant Metalia

Reputation: 30638

try to use

#include <stdio.h>

int main(){

    FILE *f; 
    char ch[5];
    f = fopen("a.txt", "r"); //use fopen
    fgets( ch, 4, f); 
    ch[4] = NULL;
    printf("%s", ch); // modification here pass the address of an array to printf
    return 0;
}

try following example from the refereed site

/* fgets example */
#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [5];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     if ( fgets (mystring , 5 , pFile) != NULL )
       puts (mystring);
     fclose (pFile);
   }
   return 0;
}

refer http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

you can also use

fgetc() :Get character from stream (function)

Upvotes: 0

Niall Byrne
Niall Byrne

Reputation: 2460

Couple of quick changes.

  1. I think you want to use fopen rather than open here, since you used a file pointer.
  2. You need to increase the bytes read to 5, the last one is terminated by a null by fgets.

     int main() {
    
         FILE *f; 
         char ch[5];
         f = fopen("a.txt", "r");
         fgets( ch, 5, f); 
         printf("%s", ch);
         return 0;
    
     }
    

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

You'll want to do

    printf("%s", ch);

For the % format, the argument is a pointer to characters; by passing a single character by value, you're telling printf to interpret that character's ASCII value as a pointer, and that's going to blow up on you; i.e., if the character is a 1, which is ASCII 49, then it's going to look at byte 49 in memory for a string -- and looking down there is generally verboten.

But secondly, I see you're calling open() instead of fopen(). You must use fopen() or you won't get a FILE* as you're expecting.

Both of these individually would likely cause a segfault -- you'll need to fix them both.

Upvotes: 2

rdo
rdo

Reputation: 3982

try to use "fopen" instead just "open"

Thanks.

Upvotes: 2

Related Questions