FILE pointer as arguement?

This is a discussion on FILE pointer as arguement? within the C Programming forums, part of the General Programming Boards category; Can you pass FILE pointers as arguements to a function? When I do it I get segmentation error. FILE * ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    57

    FILE pointer as arguement?

    Can you pass FILE pointers as arguements to a function? When I do it I get segmentation error.

    FILE * k;
    void function(FILE *p);

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    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 {
                // ...
            }
        }
    }

  3. #3
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    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()...
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    57
    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)

    Code:
    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);
    }
    }
    //after run function try use fgets on p, get segmentation error

    I can pass a file pointer that has already been opened to a function and use fgetpos() on it successfully

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    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.
    Hope is the first step on the road to disappointment.

  6. #6
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    >> gets(fetch);

    Often frowned upon! It's better to use getline(); gets doesn't flush he buffer. Read this guy's sig.

  7. #7
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Quote Originally Posted by twomers
    >> 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.

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by MDofRockyView
    but it does leave a newline character
    May. So you should check first and not just do this.
    Code:
    filename[strlen(filename) - 1] = '\0';
    Much like it says in the FAQ.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    >> 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.

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by MDofRockyView
    Does the fgets function add the newline character? If so, why do you have to check for it, if that were the case.
    No, it retains it if it is there. If it isn't there, then what is it that you are overwriting?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    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.)

    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);
    }
    ...
    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.
    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:
    Code:
    fseek(streamp, 0L, SEEK_SET);
    into the main function also causes an access violation error!?
    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:
    Code:
    printf("%s","test");
    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!!!!?
    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.
    Last edited by @nthony; 06-29-2006 at 01:49 PM.

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    You are not providing enough arguments to fscanf for one. Why aren't you using fgets? [edit]Or fgetc?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by MDofRockyView
    I'll take my chances by using a large buffer, but I should check for an error on the return value of fgets.
    Taking chances isn't smart programming.


    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    Quote Originally Posted by Dave_Sinkula
    You are not providing enough arguments to fscanf for one. Why aren't you using fgets? [edit]Or fgetc?
    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 :S
    Also, for thoroughness, I've tried both fscanf and fgets, both resulting in the same error...

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by @nthony
    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 :S
    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.

    [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;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

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

Similar Threads

  1. Problems with file pointer in functions
    By willie in forum C Programming
    Replies: 6
    Last Post: 11-23-2008, 12:54 PM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM

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