Thread: problem on function

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    13

    problem on function

    i am writing a program to count number of paragraphs
    and it can successfully run

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    	int para = 0;
    	char ch;
    	FILE *fp = fopen("InFile.txt", "r");
    	
    	if(fp==NULL) {
    		printf("Cannot open file for reading!");
    		return 1;
    	
    	
    	}
    	
    	while((ch=fgetc(fp))!=EOF) {
    		if(ch=='\n')
    		para++;
    	}
    	
    	fclose(fp);
    
    	printf("number of paragraphs is : %d\n", para+1);
    	
    	getchar();
    	
    	return 0;
    }

    however, i would like to make it into a function...

    then i change it to::
    Code:
    #include <stdio.h>
    
    void total_paragraph(FILE*infile)
    {
    int main(int argc, char *argv[]) {
    	int para = 0;
    	char ch;
    	FILE *fp = fopen("InFile.txt", "r");
    	
    	if(fp==NULL) {
    		printf("Cannot open file for reading!");
    		return 1;
    	
    	
    	}
    	
    	while((ch=fgetc(fp))!=EOF) {
    		if(ch=='\n')
    		para++;
    	}
    	
    	fclose(fp);
    
    	printf("number of paragraphs is : %d\n", para+1);
    	
    	getchar();
    	
    	return 0;
    }
    }
    then it shows something below [pink circle]...
    what happen?

    thank you very much

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Local functions are illegal.
    You nested main within your total_paragraph function. Put main outside, put all the code inside your function, open the file (and probably close it) in main, then call your function to do the rest of the work.

    You can also use fgets to read line-by-line instead of reading char-by-char. There was a topic on that not long ago.
    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.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    25
    hello everybody,
    Quote Originally Posted by Elysia View Post
    ........ open the file (and probably close it) in main .....
    and why is better to open and close the file in main?

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Probably because he has his function set to take a FILE *, which means the FILE * must already be pointing to a valid FILE object opened for reading (in this case). This means the file should already be opened, most likely in main() (since that's the only other function he has).

    It's also not a good idea to have another function close a file, unless you specifically want that behavior and are aware that this function will close the file you have. Usually, that's not a good idea because if you ever want the file to stay open, you can't use the function.

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    25
    i see now!
    and what about
    Code:
    #include <stdio.h>
    
    void total_paragraph ( FILE *infile );
    
    int main ( void )
    { 
        FILE *fp = NULL;
        
        total_paragraph ( fp );
       
       return 0;
    }
    
    void total_paragraph ( FILE* infile )
    {
       bla bla;
    }
    it's ok with that? Make sense?

    PS (off topic)
    how can modify my signature. There is no option in "edit profile" or "edit options"
    thank you

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    What about it? It's not OK to send a NULL pointer if the function expects a non-NULL pointer, so it depends upon the definition of total_paragraph().

  7. #7
    Registered User
    Join Date
    Dec 2007
    Posts
    13
    thanks

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    That example is definitely not OK.
    If the function is required to open the file itself, then it should not take any arguments. By specifying that it takes a FILE*, then it means it's expecting an open file to process and that also makes more sense since the function is named total_paragraph(s) (count the number of paragraphs in a file) and it also adds more flexibility to your program. You can call the function with any instead of just a specific file.

    To change signature, it's under User CP -> Edit Signature.
    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.

  9. #9
    Registered User
    Join Date
    Dec 2007
    Posts
    25
    I will be back tomorow,

    Happy New Year to everyone!!!

  10. #10
    Registered User
    Join Date
    Dec 2007
    Posts
    25
    ok, here we are,

    Code:
    #include <stdio.h>
    #include <stdlib.h>   /* exit */
    
    void function ( FILE *out, char *filename );
    
    int main ( int argc, char *argv[ ] )
    {
        FILE *fp = NULL;
        function ( fp, argv[ 1 ] );   /* argv[ 1 ] is the file name */
    
        return 0;
    }
    
    void function ( FILE *out, char *filename )
    {
        char string[ ] = "bla  bla bla";
        out = fopen ( filename, "w" );
    
        if ( out == NULL )
        {
             printf ( "can't write %s\n", filename );
    	 exit ( 1 );
        }
    
        fprintf ( out, "%s", string );
        fclose ( out );
    }
    I dont know how the above looks, but it works fine ( and is also flexible, i guess).

    My point is that is good to initialise a pointer before using it.

    Please consider that i am new in C, and my english is not perfect.

    ps. There is no option UserCP->edit signature

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    That's wrong.
    I still suggest main open and close the file.
    Out just works like a local variable and is always NULL when passed to the function. Main won't see the changed handle either, so the code is rather useless.
    Make main open the file instead and then pass it to the function.

    There is a user cp -> edit signature. I don't know if there's a requirement on a minimum no. of posts, however.
    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.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I dont know how the above looks, but it works fine ( and is also flexible, i guess).

    My point is that is good to initialise a pointer before using it.
    Elysia's concern is less on initialising the pointer than on function design. From your code example, it is clear that the rather poorly named function function() takes a filename, opens a file, and then writes a string to that file and closes it. As such, it certainly does not need to take a FILE pointer, so why pass a FILE pointer in the first place?

    By only having the filename as the argument, one makes it clear that the function is self-contained in its file handling. Your code would then look like:
    Code:
    #include <stdio.h>
    #include <stdlib.h>   /* exit */
    
    void function ( char *filename );
    
    int main ( int argc, char *argv[ ] )
    {
        function ( argv[ 1 ] );   /* argv[ 1 ] is the file name */
    
        return 0;
    }
    
    void function ( char *filename )
    {
        char string[ ] = "bla  bla bla";
        FILE *out = fopen ( filename, "w" );
    
        if ( out == NULL )
        {
            printf ( "can't write &#37;s\n", filename );
            exit ( 1 );
        }
    
        fprintf ( out, "%s", string );
        fclose ( out );
    }
    Alternatively, you could pass a FILE pointer only, in which case the function assumes that the file has been opened and merely performs the writing of the string.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Dec 2007
    Posts
    25
    thank you for instant responces,
    cheers.

  14. #14
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    You should also check that argv[1] exists, by doing this:
    Code:
    if (argc < 2)
    {
        fputs("No file specified\n", stderr);
        return -1;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 10-29-2008, 06:33 AM
  2. wxWidgets link problem
    By cboard_member in forum C++ Programming
    Replies: 2
    Last Post: 02-11-2006, 02:36 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Problem with function pointers
    By vNvNation in forum C++ Programming
    Replies: 4
    Last Post: 06-13-2004, 06:49 AM