Monday, May 24, 2010

What's the error in this c program?

I keep getting a segmentation fault and never get into the loop here. I know it's a problem with the open call.





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.%26gt;


#include %26lt;ctype.h%26gt;





int main(int argc, char* argv[]) {


char c;


int argIndex;





(integer declarations here);





FILE* infile = stdin;


infile = fopen("infile", "r");





The program is supposed to take the file name from the standard input, open it, and run it through the loop, but I keep hitting a segmentation fault before it even hits the loop. Anybody know what I'm messing up? Thanks so much!

What's the error in this c program?
Read this carefully:


You need to read the file name from stdin.


Then once you get the file name, fopen it and read the chars from the file.





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt; /* fixed missing h */


#include %26lt;ctype.h%26gt;





int main(int argc, char* argv[]) {


char c;


int argIndex;





(integer declarations here);





FILE* infile = stdin; /* no need to do this */


infile = fopen("infile", "r");


/* the above line is wrong.


You are attempting to open a file named infile.


You already assigned a value to infile in the line before.


And you are not checking to see if the fopen was successful.


*/


Suggested fix:


before calling fopen, read in the name of the file you want to read from stdin:


c = fgetc(stdin);


char filename[200] = { '\0'}; /*create a string to keep the file name */


int e = 0; /* index to end of string */


/* keep reading until user presses enter key */


while( c != EOF %26amp;%26amp; c != '\n' )


{


/* append char */


filename[e++] = c; filename[e] = '\0';


c = fgetc(stdin);


}


FILE *fp = fopen(filename, "r")


if ( !fp )


{


printf("Could not open file %s\n", filename);


exit(1);


}


while ( (c = getc(infile)) != EOF ) {


nChars++;


etc
Reply:dude i am confused i only recignize the first few lines of code.
Reply:???hi pie????
Reply:A segfault occurs when a program attempts to access memory it's not allowed to access, or write in a read-only sector. I don't know why this program would be doing that - maybe you need more memory. Or maybe all of your RAM is read only. And if that's the case, how are you online?
Reply:can you post the whole code up?





I assume it is just a typo here but have you noted that your second #include line is incorrect?





It should read:


  #include %26lt;stdlib.h%26gt;


No comments:

Post a Comment