fscanf seg fault

This is a discussion on fscanf seg fault within the C Programming forums, part of the General Programming Boards category; Hi all, BRAND new to programming in C.. in fact this is my first real program. I have an assignment ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    18

    fscanf seg fault

    Hi all,

    BRAND new to programming in C.. in fact this is my first real program.

    I have an assignment I've been trying to complete and I'm getting an error (seg fault) I was hoping someone could shed some light on.

    The program is supposed to take an undefined number of arguments. (well more than one) The first one is the output file to append other files to (or just create if no other args supplied) and all other arguments (no specified number) are files to append to the output file. I have to use fopen, fscanf, fprintf and fclose.

    My problem is I'm getting a seg fault when I tried to implement fscanf. I assume it's because I'm not assigning something properly, I just don't know what!

    Any help on the seg fault would be great.

    This is the code I have so far.. messy as it is
    Code:
    # include <stdio.h>
    
    FILE *output, *input, *buffer;									/* declarations*/
    
    int i,j;
    char buf[80];
    
    
    
    int main (int argc, char *argv[])
    	{
            if ( argc < 2 ) 								/* Error message if no Args entered */
    		{
    		printf ("\n **************** \n Not enough Arguments Supplied\n ****************\n");
    		printf ("\nPlease enter an Output file to append to, followed by any input files\n \n");
    		return 1;
    		}	
    	else  										/*Output file opened or created */
    		{
    		output = fopen(argv[1], "a+");
    		}
    
    	if (argc == 2)									/*If only one Arg entered*/
    		{
    		printf ("\nA New Blank file:  '%s'  was created \n\nNo input files were supplied to append\n\n", argv[1]);
    		return 0;
    		}
    	else										/* start append section */
    		{
    		i = argc -2;
    		j = 2;
    		printf ("The number of files to append to: %s was %d\n",argv[1], i);
    	
    	
    
    
    		while (i > 0)
    			{
    			input = fopen("argv[j]", "r");
    
    			fscanf (input, "%s", buf);
    			printf("buf", buf); 						
      			fclose(input);
    			j ++;
    			i --;
    			}
    		}
    	}

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    I doubt the file "argv[j]" exists. You probably want to (a) open argv[j] instead, and (b) check whether fopen actually succeeds before blithely using the result.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Code:
    char buf[80];
    ....
    fscanf (input, "%s", buf);
    Don't do this.

    Instead do:
    Code:
    #define STR(arg) #arg
    #define BUF_SIZE 80
    char buf[BUF_SIZE];
    ....
    fscanf (input, "%" STR(BUF_SIZE) "s", buf);
    Or use another function instead of fscanf.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Registered User
    Join Date
    Aug 2009
    Posts
    18
    Thanks for the answers guys.

    With the argv[j],
    I was trying to increment the value of 'j' to go through all the arguments until i was 0.

    I've tried to add an error check to see if fopen worked,
    Don't know if it's correct, but no problems showed on compile.

    I added the code you suggested King Mir , and thanks for the advice!
    I'm getting a compile error now on the fscanf line,
    it says
    unknown conversion type character 'B' in format

    The code is currently this,
    any ideas?

    Code:
    # include <stdio.h>
    #define STR(arg) #arg
    
    #define BUF_SIZE 80
    
    
    char buf[BUF_SIZE];
    FILE *output, *input, *buffer;									/* declarations*/
    
    int i,j;
    
    
    
    int main (int argc, char *argv[])
    	{
            if ( argc < 2 ) 								/* Error message if no Args entered */
    		{
    		printf ("\n **************** \n Not enough Arguments Supplied\n ****************\n");
    		printf ("\nPlease enter an Output file to append to, followed by any input files\n \n");
    		return 1;
    		}	
    	else  										/*Output file opened or created */
    		{
    		output = fopen(argv[1], "a+");
    		}
    
    	if (argc == 2)									/*If only one Arg entered*/
    		{
    		printf ("\nA New Blank file:  '%s'  was created \n\nNo input files were supplied to append\n\n", argv[1]);
    		return 0;
    		}
    	else										/* start append section */
    		{
    		i = argc -2;
    		j = 2;
    		printf ("The number of files to append to: %s was %d\n",argv[1], i);
    	
    	
    
    
    		while (i > 0)
    			{
    			input = fopen(argv[j], "r");
    
    			if (input = NULL)
    				{
    				printf ("\nInput File Failed to Open\n");
    				return 1;
    				}
    			else
    				{
    				fscanf (input, "%" STR(BUF_SIZE) "s", buf);
    				printf("buf", buf); 						
      				fclose(input);
    				j ++;
    				i --;
    				}
    			}
    		}
    	}

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    I compiled your code with codepad, and it compiles fine. What compiler are you using? Cause that looks like a serious preprocessor bug.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    18
    GCC
    first with pedantic, then without, same error

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Hrm. My version of gcc reports a warning on the next line ("too many arguments for format") but not on the line with STR on it. (It shouldn't, but does it make a difference what order you do the defines in?)

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Hm. I swear I remmeber that working before, but looks like it doesn't. Well in this case you can either hard code "%80s", or you can make that sting as a macro just like BUFF_SIZE:
    Code:
    #define BUF_FORMAT "%80s"
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  9. #9
    Registered User
    Join Date
    Aug 2009
    Posts
    18
    OKay,
    Well it's compiling again,
    but I'm back to having a seg fault

    Is there perhaps a more standard way to run through an undefined number of arguments? This was just what I thought up.

    I appreciate all the help by the way

    Code:
    # include <stdio.h>
    #define STR(arg) #arg
    
    #define BUF_SIZE 80
    
    #define BUF_FORMAT "%80s"
    
    char buf[BUF_SIZE];
    FILE *output, *input, *buffer;									/* declarations*/
    
    int i,j;
    
    
    
    int main (int argc, char *argv[])
    	{
            if ( argc < 2 ) 								/* Error message if no Args entered */
    		{
    		printf ("\n **************** \n Not enough Arguments Supplied\n ****************\n");
    		printf ("\nPlease enter an Output file to append to, followed by any input files\n \n");
    		return 1;
    		}	
    	else  										/*Output file opened or created */
    		{
    		output = fopen(argv[1], "a+");
    		}
    
    	if (argc == 2)									/*If only one Arg entered*/
    		{
    		printf ("\nA New Blank file:  '%s'  was created \n\nNo input files were supplied to append\n\n", argv[1]);
    		return 0;
    		}
    	else										/* start append section */
    		{
    		i = argc -2;
    		j = 2;
    		printf ("The number of files to append to: %s was %d\n",argv[1], i);
    	
    	
    
    
    		while (i > 0)								/*Loop through all input files*/
    			{
    			input = fopen(argv[j], "r");
    
    			if (input = NULL)						/*Check fopen worked */
    				{
    				printf ("\nInput File Failed to Open\n");
    				return 1;
    				}
    			else
    				{
    				fscanf (input, BUF_FORMAT , buf);
    				printf("%s", buf); 						
      				fclose(input);
    				j ++;
    				i --;
    				}
    			}
    		printf ("\nFiles Appended Successfully");				/*Files Appended Successfully*/
    		return 0;
    		}
    	}
    Last edited by mercuryfrost; 08-19-2009 at 08:39 PM.

  10. #10
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    OOPS
    Code:
    if (input = NULL)

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    > fscanf (input, "%" STR(BUF_SIZE) "s", buf);
    Except this does not account for the \0, so it will add BUF_SIZ chars and a \0 (you lose)

    > Or use another function instead of fscanf.
    Like fgets for example, where BUF_SIZ can be used directly without any macro magic.
    Eg.
    char buff[BUF_SIZ];
    fgets( buff, BUF_SIZ, input );
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Registered User
    Join Date
    Aug 2009
    Posts
    18
    Must use fscanf unfortunately.

    Also, What do you mean by OOPS tabstop?

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by mercuryfrost View Post
    Must use fscanf unfortunately.

    Also, What do you mean by OOPS tabstop?
    "Oops" means "the part in red is incredibly, amazingly, embarrassingly wrong".

  14. #14
    Registered User
    Join Date
    Aug 2009
    Posts
    18
    @ Tabstop

    Yep, well as I said, this is my first go at C
    Embarrassment is secondary to learning!


    Okay...

    Not sure what I changed to make it work, but with a few little changes this code is now compiling and running for me...

    Code:
    # include <stdio.h>
    #define STR(arg) #arg
    
    #define BUF_SIZE 80
    
    #define BUF_FORMAT "%80[^\n]s"
    
    char buf[BUF_SIZE];
    FILE *output, *input, *buffer;									/* declarations*/
    
    int i,j;
    
    
    
    int main (int argc, char *argv[])
    	{
            if ( argc < 2 ) 								/* Error message if no Args entered */
    		{
    		printf ("\n **************** \n Not enough Arguments Supplied\n ****************\n");
    		printf ("\nPlease enter an Output file to append to, followed by any input files\n \n");
    		return 1;
    		}	
    	else  										/*Output file opened or created */
    		{
    		output = fopen(argv[1], "a+");
    		}
    
    	if (argc == 2)									/*If only one Arg entered*/
    		{
    		printf ("\nA New Blank file:  '%s'  was created \n\nNo input files were supplied to append\n\n", argv[1]);
    		return 0;
    		}
    	else										/* start append section */
    		{
    		i = argc -2;
    		j = 2;
    		printf ("\nThe number of files to append to: %s was %d\n\n",argv[1], i);
    	
    	
    
    
    		while (i > 0)								/*Loop through all input files*/
    			{
    			/*printf ("%s\n", argv[j]);*/					/* Used for Error Checking*/
    			input = fopen(argv[j], "r");
    
    			if (!input)						/*Check fopen worked */
    				{
    				printf ("FAILURE! Input File: %s Failed to Open or does not exist\n", argv[j]);
    				}
    			else
    				{
    				fscanf (input, BUF_FORMAT , buf);
    				/*printf("%s\n", buf);*/    				/* Used for Error Checking */
    				fprintf (output, "%s\n", buf);						
      				fclose(input);
    				printf ("SUCCESS! Input File: %s was Successfully appended\n", argv[j]);				
    				}
    			j ++;
    			i --;
    			}
    		printf ("\nFiles Appended Successfully\n\n");				/*Files Appended Successfully*/
    		return 0;
    		}
    	}

    Any comments are welcome.

    And a Big thank you for all the help all!

    Also, how would one start implementing this same code using open, read, write, and close rather than fopen, fscanf, fprintf, and fclose?
    Last edited by mercuryfrost; 08-20-2009 at 09:23 AM.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,031
    Why do you need to?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf causes a SEGMENTATION FAULT
    By yougene in forum C Programming
    Replies: 15
    Last Post: 12-29-2008, 12:11 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 04:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 02:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 09:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 04:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21