Can you pass FILE pointers as arguements to a function? When I do it I get segmentation error.
FILE * k;
void function(FILE *p);
Printable View
Can you pass FILE pointers as arguements to a function? When I do it I get segmentation error.
FILE * k;
void function(FILE *p);
Actually, I think it would be better to return whatever fp no matter what happens and let the user decide what to do with it.Code:FILE* OpenReadOnlyFile(const char* file) {
FILE* fp = fopen(file, "r");
return fp;
}
int main(int argc, char** argv) {
if(argc > 1) {
FILE* myFile = OpenReadOnlyFile(argv[1]);
if(myFile == NULL) {
// ...
} else {
// ...
}
}
}
darsunt: Is the file pointer valid? Did you initialize it to NULL / check the return value on fopen() ? Perhaps show some code?
MDOfRockyView: What is the point of the second argument to OpenAFile? You can't return any values through it (and you do so through the return value anyways...) And you pass garbage to that when you call it from main()...
I wrote this function to take a FILE pointer as arguement and open it to a file. The function itself runs without complaint, so the file apparently was opened, but when I try to use fgetc on the supposedly opened FILE pointer I get a segmentation fault (memory error)
//after run function try use fgets on p, get segmentation errorCode:void open_file(FILE * p)
{
char fetch[20];
printf("Enter name of file: ");
gets(fetch);
if(!(p=fopen(fetch,"r+t")))
{
printf("Cannot open file\n");
exit(1);
}
}
I can pass a file pointer that has already been opened to a function and use fgetpos() on it successfully
If you pass an integer to a function, how can you fill it so that it retains any alterations you've made to it? If you can answer that, you've just answered how to do the same thing with a FILE pointer, or any variable for that matter.
If you can't, try reading the post right before yours.
Quzah.
>> gets(fetch);
Often frowned upon! It's better to use getline(); gets doesn't flush he buffer. Read this guy's sig.
getline() is not a standard C function, fgets() is, and is the preferred alternative to gets(). The problem with gets() has nothing to do with "flushing the buffer", and is wholly to do with not allowing any limit on amount of characters read to be specified, thus being able to be overflowed.Quote:
Originally Posted by twomers
May. So you should check first and not just do this.Quote:
Originally Posted by MDofRockyView
Much like it says in the FAQ.Code:filename[strlen(filename) - 1] = '\0';
>> not allowing any limit on amount of characters read to be specified
Good point. Sorry about that. I haven't seen gets(); in a while, knew there was something bad about it, and and assumed it was something to do with the buffer.
...
>> getline() is not a standard C function
Also a good point. I've been doing C++ for the past long time, and I think it's standardised there, so suggested it.
No, it retains it if it is there. If it isn't there, then what is it that you are overwriting?Quote:
Originally Posted by MDofRockyView
Hello all, I'm having a similar problem with FILE pointers as arguements, except I'm using them in a stream capacity (as pointers to a stream created by the popen() function).
Everything compiles fine, but I get access violation errors (in Quincy; which is the equivalent to a memory error like described by the OP) whenever I try to use a locally cloned pointer in the fscanf() function. (i.e. the locally cloned pointer in the function "get_num_lines", when passed to the fscanf function causes an access error.)
Now I know somehow it must be possible to pass FILE pointers to a function without causing error because the fscanf function does it! (though I can't find the source code for it), but when I try to do the same thing it results in error.Code:...
int
main(void)
{
int num_lines, i;
char **s;
FILE *streamp;
streamp = popen(COMMAND, "r");
//WORKS HERE
fscanf(streamp," %s");
// pass stream pointer to function
num_lines = get_num_lines(streamp);
s = (char **) calloc(num_lines, sizeof(char *));
...
...
}
int
get_num_lines(FILE *streamp)
{
int num_lines = 0;
//BUT NOT HERE
//CAUSES ACCESS ERROR
while(fscanf(streamp," %s") != EOF)
{
++num_lines;
//ignore white spaces
while(fgetc(streamp) == SPACE)
{
fscanf(streamp,"%s");
}
}
rewind(streamp);
return(num_lines);
}
...
As shown above, when I pop the same error-causing line from the get_line_function (fscanf(streamp," %s")) into the main body instead, it works fine with no errors.
Just in case, in the get_line_function, I tried using the ORIGINAL main pointer to the stream by instead passing a pointer to pointer argument (so the function expected a FILE **streamp, and then I would pass &streamp to it from main), but it lead to the same problem. Next, I tried using void pointers (in case FILE* did not accurately encase streams created by popen()), but to no avail, same problem there too...
So my question is, both pointers (the one in main, and the one locally cloned in get_num_lines) point to the SAME stream, yet any attempt to access the stream through the cloned pointer leads to an error, why is this? is there something about the original pointer that is not being passed correctly onto the called function? And if so, what is it that makes fscanf() able to pass cloned pointers without problem?
Thanks for any help/insight you can give me!
p.s. this may also be a stream-related problem, as sticking:
into the main function also causes an access violation error!?Code:fseek(streamp, 0L, SEEK_SET);
The stream pointed to by the pointer returned by the popen() function seems to be different than a regular stream; if anyone knows anymore about streams/pipes (between the program and the shell command subprocess/child) created by the popen function please explain!
p.s.s, VERY WIERD:
I left the program completely UNCHANGED except for adding this:
into the main function BEFORE calling the get_line_function, and now the error has disappeared. I am absolutely confounded... how in any way possible could a printf statement affect the reading of another stream that is completely unrelated to it!!!!?Code:printf("%s","test");
did the printf statement somehow magically clear some invisible buffer or something, I am at a complete loss for understanding... but I'll go with it and see how far it takes me.
You are not providing enough arguments to fscanf for one. Why aren't you using fgets? [edit]Or fgetc?
Taking chances isn't smart programming.Quote:
Originally Posted by MDofRockyView
Quzah.
the third fscanf argument (a list of pointers) can be ommitted, but for the sake of thoroughness, I also tried filling them with a pointer to a string which yeilded the same result :SQuote:
Originally Posted by Dave_Sinkula
Also, for thoroughness, I've tried both fscanf and fgets, both resulting in the same error...
Then where is it to write the string? Why not post a snippet that demonstrates the issue(s). [edit]And you'll not just want a pointer, but a pointer to some memory to which you can write. Or make it simple and use an array.Quote:
Originally Posted by @nthony
[edit=2]Assuming you are not hosing things up before you get to get_num_lines, would this work?Code:int get_num_lines(FILE *file)
{
int ch, prev = '\n' /* so empty files have no lines */, lines = 0;
while ( (ch = fgetc(file)) != EOF ) /* Read all chars in the file. */
{
if ( ch == '\n' )
{
++lines; /* Bump the counter for every newline. */
}
prev = ch; /* Keep a copy to later test whether... */
}
rewind(file);
if ( prev != '\n' ) /* ...the last line did not end in a newline. */
{
++lines; /* If so, add one more to the total. */
}
return lines;
}
No actually you can't. You're thinking of *printf. Well...you can omit the list of arguments, assuming all of your scan codes are actually set to skip conversion. Yours aren't.Quote:
Originally Posted by @nthony
Which is?Quote:
Originally Posted by @nthony
Quzah.
I honestly think its more a question of rushing that purposely creating bugs. The software engineers are fairly competent, however they are human as well. We all make mistakes and sometimes they can get lost in thousands of lines of code. Some errors are VERY VERY hard to find, and much less fix. If you've written a program with others you should know... rarely do their styles fully complement each other.Quote:
Originally Posted by MDofRockyView
Also, in fscanf, its true the variables are "optional" but thats kinda like using scanf without the optionals there right? Is there any particular reason to be so imprecise?
I don't use Microsoft as my poster child of how to write good code. Don't be lazy and write sloppy code that'll only work in the most stringent of conditions. Yes, you know how your code works, what format the data should be in an how to pass that data for it to work. But will a future user? Chances are, no - users are stupid, and do odd stuff. And when they pass data that isn't up to what you thought it would be - would you rather have accounted for it, and have your program handle it gracefully, even if "gracefully" was an error message informing the user of what went wrong? Or would you rather it core dump / seg fault in his face, causing him to curse at the software you wrote? It's your code; but will it be sloppy or bullet-proof? Sure, you can't predict or handle every problem, but you can cover the minimum of issues.Quote:
Originally Posted by MDofRockyView
Never forget the fifth commandment: "Thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest 'foo' someone someday shall type 'supercalifragilisticexpialidocious'."
Quote:
"Thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest 'foo' someone someday shall type 'supercalifragilisticexpialidocious'."
and still today the world's first program is still experiencing undefined behavior, and the standard output tablet is still being chiseled. Curs'd be the programmer's head. :PCode:What dost thou type?
supercalifragilisticexpialidocious
I shall process...
That was a stupid joke for something so fun to type.
Well you've already proven that... :rolleyes:Quote:
Originally Posted by MDofRockyView
Quzah.