Question:
What's the error in this c program?
hockeychick00014
2008-01-22 22:50:44 UTC
I keep getting a segmentation fault and never get into the loop here. I know it's a problem with the open call.

#include
#include
#include

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!
Five answers:
TristanVR
2008-01-23 07:33:53 UTC
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

#include /* fixed missing h */

#include



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 && 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
I'm a great person
2008-01-22 23:00:05 UTC
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?
tgtips
2008-01-22 23:21:18 UTC
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
Punjabi Smarty
2008-01-22 23:22:12 UTC
dude i am confused i only recignize the first few lines of code.
2008-01-22 22:57:47 UTC
???hi pie????


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...