Thread: i have a seg fault

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    9

    i have a seg fault

    when i try to open the file i get a seg fault always. any help is appreciated.

    Code:
    void open_batch()
    {
       char f[100];
       char c;
       int a = 0, b = 0;
       int eof = 0;
       int d, e, g, h, i, j, k;
       printf("Please enter the file you wish to run: ");
       scanf("%s", f);
       if((fopen(f,"rt") == NULL))
       {
          printf("No such file");
       }
       else
       {
          printf("File exists");
       }
    
       while(eof == 0)
       {
          c = fgetc(file);
          ...
          ...

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Where are you actually setting eof to something other than 0? Were you trying to use the standard EOF?
    If you understand what you're doing, you're not learning anything.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    char c;
    int a = 0, b = 0;
    int eof = 0;
    int d, e, g, h, i, j, k;
    Try thinking up better names for your variables, and remove all the ones you don't need.
    Apart from some obvious exceptions (eg. x,y for coordinates, i,j for loops, and perhaps c for chars), you should have meaningful names for things.
    So for example char f[100]; would be char filename[100];

    > if((fopen(f,"rt") == NULL))
    Simplify!
    You're ignoring the return result.
    FILE *file = fopen( f, "rt" );
    if ( file == NULL )

    > c = fgetc(file);
    1. You didn't declare file anywhere
    2. c should be declared as int c; not char c;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting a seg fault
    By ammochck21 in forum C Programming
    Replies: 11
    Last Post: 01-23-2009, 05:27 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM