#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0

    Strange C code error....


    Hi everybody, i am a beginner at C ... i often encounter some strange problems. :chomp: :chomp: .. so help me out guys..

    this is a C code that prints the contents of a file...
    eventhough both the codes are same.. the one in the bottom (code 2) doesn't work ..i tried many times but " code 2 " doesn't work but "code 1" does...i dont get any output when i run "code 2"

    code 1:

    int main()
    {
    FILE *fp,*tp;
    char i,j;
    tp=fopen("shapes.c","rt");
    while((fscanf(tp,"%c",&j))!=EOF)
    {
    printf("%c",j);
    }
    fclose(tp);
    }





    code 2:

    int main()
    {
    FILE *fp;
    char stu;
    fp=fopen("shapes.c","rt");
    while((fscanf(fp,"%c",&stu)) !=EOF )
    {
    printf("%c",stu);
    }
    fclose(fp);
    return 0;

    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Test the value returned by fopen(). If it's NULL, then the file failed to open. That should give you a clue.

    #include errno.h . Before you call fopen, set errno to zero. Then when fopen fails (which is what I suspect, but only you can verify that), display the value of errno. Even better, call perror("fopen failed"); which will display a message such as "file not found".

    Just out of curiosity, are both programs being run in the same directory? That being the directory that also contains the file, shapes.c.

    PS

    Odd, though. You act like it just didn't output anything. If you had tried to use a NULL FILE pointer, it should have blown up in your face, which would have been difficult to not notice.
    Last edited by dwise1_aol; August 29th, 2013 at 11:13 PM.
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Also, don't use italics for code listings. Instead use code tags. Italics don't preserve indenting, whereas code tags do.

    For example, here are your listings with code tags -- original indenting recovered via the Reply button:
    code 1:

    Code:
    int main()
    {
        FILE *fp,*tp;                
        char i,j;
        tp=fopen("shapes.c","rt");        
           while((fscanf(tp,"%c",&j))!=EOF)    
          {
           printf("%c",j);
          }
           fclose(tp);
    }

    code 2:

    Code:
    int main()
    {
        FILE *fp;
        char stu;
        fp=fopen("shapes.c","rt");
        while((fscanf(fp,"%c",&stu)) !=EOF )
            {
                printf("%c",stu);
            }
        fclose(fp);
        return 0;
    
    }
    BTW, code 2 demonstrates the proper way to declare and use main.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    Originally Posted by dwise1_aol
    Also, don't use italics for code listings. Instead use code tags. Italics don't preserve indenting, whereas code tags do.

    For example, here are your listings with code tags -- original indenting recovered via the Reply button:
    code 1:

    Code:
    int main()
    {
        FILE *fp,*tp;                
        char i,j;
        tp=fopen("shapes.c","rt");        
           while((fscanf(tp,"%c",&j))!=EOF)    
          {
           printf("%c",j);
          }
           fclose(tp);
    }

    code 2:

    Code:
    int main()
    {
        FILE *fp;
        char stu;
        fp=fopen("shapes.c","rt");
        while((fscanf(fp,"%c",&stu)) !=EOF )
            {
                printf("%c",stu);
            }
        fclose(fp);
        return 0;
    
    }
    BTW, code 2 demonstrates the proper way to declare and use main.
    @dwise1_aol -- sorry i will use the CODE TAGS..
    yeah i missed the return statement....
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    Both the progs use the same file... i did the CODE 1 sometime ago.. and it works.. CODE 2 doesn't output anything... i am running both the codes in side by side tabs ... i will check the return value of fopen(); ... never used errno.h ..will try that too, thnx a lot..
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Originally Posted by kurosaki
    Both the progs use the same file... i did the CODE 1 sometime ago.. and it works.. CODE 2 doesn't output anything... i am running both the codes in side by side tabs ...
    None of that tells me anything.

    "Both the progs use the same file." Does that mean that they both try to open the same file? Or that code 2 is a modification of code 1? If it is the latter, then is code 2 in the same directory as code 1? I ask that, because that could place the executable in the same directory which would also be the same directory of the file you're trying to open.

    Running both programs in side-by-side tabs means absolutely nothing. What directories are they running in? The same directory? Or a different one? If different, then did you also copy the file you're trying to open from code 1's directory to code 2's?

    fp=fopen("shapes.c","rt");
    says to look in the current working directory for that file. When a program executes, it does so within an environment -- the concept of an environment is much stronger in a shell (AKA "console", AKA "command prompt", AKA "command line", AKA "terminal", AKA "DOS window") than with a GUI, but a GUI also has an environment that includes the current working directory. Normally, the current working directory starts out being the same directory as where the executable resides, but the program can change it (eg, with the chdir() change directory function).

    So if you tell fopen to open that file in the current working directory and the file is not in the current working directory, then it will not be able to open it. That is why I keep asking what directory everything is in.

    If you have no idea what a directory is, then please let me know. The GUI "desktop" paradigm calls them "folders", but I'm an old DOS'er who worked with MS-DOS' directory structure every day for more than a decade, so I call them what they are.

    Originally Posted by kurosaki
    i will check the return value of fopen(); ... never used errno.h ..will try that too, thnx a lot..
    You need to always test the return value of fopen before you use it. That is a minimal requirement of good programming practice.

    Using errno.h is not required, but can be very useful when you're trying to figure out why something doesn't work. It is always far better to actually know than to guess.

    Until you do check the return value of fopen and use errno to report what kind of error it's encountering, we will not be able to know what's happening here. We're depending on you to help us to give you the answer you seek.
  12. #7
  13. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    C is a lean, mean programming language which was created by super-programmers for their own use. It's based on quite a different philosophy than most newer languages: while the newer languages go out of their way to protect you from yourself, C will readily allow you to shoot yourself in the foot because you, being the programmer, must know what you are doing.
    Originally Posted by Doug Gwyn
    UNIX was not designed to stop its users from doing stupid things, as that would also stop them from doing clever things.
    Part of C's lean, mean philosophy extends to run-time errors. C does not perform run-time checking for indexing outside of an array's bounds or for arithmetic overflow, because that would slow it down. As a result, it is the programmer's responsibility to detect and handle such incidents.

    When you check errno, you will at first find it of no use since errno is simply a number. To find out what the number means, you would need to consult the errno.h header file, where you will find a list of macros. In the errno.h header file for my copy of MinGW gcc, that list starts with:
    Code:
    #define EPERM		1	/* Operation not permitted */
    #define	ENOFILE		2	/* No such file or directory */
    #define	ENOENT		2
    #define	ESRCH		3	/* No such process */
    #define	EINTR		4	/* Interrupted function call */
    #define	EIO		5	/* Input/output error */
    #define	ENXIO		6	/* No such device or address */
    #define	E2BIG		7	/* Arg list too long */
    #define	ENOEXEC		8	/* Exec format error */
    #define	EBADF		9	/* Bad file descriptor */
    #define	ECHILD		10	/* No child processes */
    #define	EAGAIN		11	/* Resource temporarily unavailable */
    #define	ENOMEM		12	/* Not enough space */
    #define	EACCES		13	/* Permission denied */
    #define	EFAULT		14	/* Bad address */
    Those macro names can be handy for two reasons. One, they assign names to the numbers, so when you read the documentation (eg, the man pages, thousands of copies of which are posted on-line) they will tell you what errors a function could throw; be aware that the same error may have a different errno value in a different compiler, so while the actual numbers may change, the names should remain the same. Two, in your code you can make explicit tests of errno against a macro name; eg, in sockets programming when you're using non-blocking sockets, you want to test errno against EWOULDBLOCK or EAGAIN.

    But usually, you want to display an error message instead of a number, in which case you can use perror (prototype in stdio.h) to print a message to which you can add some text, or create your own message using strerror (prototype in string.h).

    I mentioned man pages. You can find them with Google; eg, man page fopen. Here is part of what a man page for fopen (http://linux.die.net/man/3/fopen) says:
    Return Value
    Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

    Errors
    EINVAL
    The mode provided to fopen(), fdopen(), or freopen() was invalid.

    The fopen(), fdopen() and freopen() functions may also fail and set errno for any of the errors specified for the routine malloc(3).

    The fopen() function may also fail and set errno for any of the errors specified for the routine open(2).
    That provided a link to the man page for open (http://linux.die.net/man/2/open, where we find 22 possible error codes. I'd rather not post all 22 here, so follow that link to look them up for yourself. But one of them is ENOENT (AKA "ENOFILE"):
    ENOENT
    O_CREAT is not set and the named file does not exist. Or, a directory component in pathname does not exist or is a dangling symbolic link.
    That is the error that I suspect you are encountering, but we won't know that until you have retrieved that errno.


    Here is your second program, "code 2", modified with error checking and reporting. The reporting style is just to demonstrate the functions and is not intended as the way you should report errors. Please note that if fopen fails, you must not use that FILE pointer!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    
    int main()
    {
        FILE *fp;
        char stu;
        
        fp=fopen("shapes.c","rt");
        if (fp == NULL)  // if fopen failed
        {
            printf("errno == %d: %s\n", errno, strerror(errno));
            perror("fopen failed");
        }
        else  // only execute if fopen succeeded
        {
            while((fscanf(fp,"%c",&stu)) !=EOF )
            {
                printf("%c",stu);
            }
            fclose(fp);
        }
        
        return 0;
    }
    There is no such file as shapes.c in the directory in which I ran it. Here is what it output when I ran it:
    C:TEST>a
    errno == 2: No such file or directory
    fopen failed: No such file or directory

    C:TEST>
    The error was ENOFILE / ENOENT. And the wording, "No such file or directory", was provided by the compiler through the functions perror() and strerror() which I used.

    Now what do you get when you apply those changes to your "code 2" and run it?

    PS

    Also, what are you using?

    For example, I used MinGW gcc. I used my favorite text editor, Note Tab Plus, to edit the source file. I opened a console (AKA "DOS window", AKA "Command Prompt") and changed the directory with CD commands (short for chdir) to navigate to the directory where my source file is. I then invoked gcc from the command line to build an executable, which I then ran in the same directory. I did all this under Windows XP.

    What compiler/integrated development environment (IDE) are you using? You mentioned "side by side tabs", so I suspect that you're using an IDE. Under what operating system? Any other specifics that you think might help? Such as whether your two programs are in two different projects which have their own separate directories, as Visual Studio will normally set up. Again, that would get us back to the question of what each project's current working directory would be and whether you had ensured that a copy of the file, shapes.c, would be present in each project's current working directory.

    Comments on this post

    • kurosaki agrees : very very helpful and super supportive...
    Last edited by dwise1_aol; August 30th, 2013 at 01:26 PM.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    sorry, both the file that i am trying to open and the .exe are in the same folder.. my confusion is that there is no difference between CODE 1 and CODE 2 ...so why one works and the other doesn't..

    "You need to always test the return value of fopen before you use it. That is a minimal requirement of good programming practice" -- thnx,didn't know that..
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    That post really helped me... errno.h gives me a "no such file or directory" error... but the file does exist.. i ran CODE 1 in dev c++(ming gw) and CODE 2 in codeblocks(borland 5.5)... even though both the codes are same,i don't get any output in codeblocks... but code 1 runs fine in dev c++..
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    Super thnx to you sir...That post about errno.h really helped me a lot . i didn't even know that there existed such a convenient way of error checking... i deleted the file and recreated it ,now both the codes do fine... i thought of file permissions, but how can CODE 1 open it then... i did cross check them on both the ides too...
    one PROG works and the other doesn't even though they have the same content ...
  20. #11
  21. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Originally Posted by kurosaki
    Super thnx to you sir...That post about errno.h really helped me a lot . i didn't even know that there existed such a convenient way of error checking... i deleted the file and recreated it ,now both the codes do fine... i thought of file permissions, but how can CODE 1 open it then... i did cross check them on both the ides too...
    one PROG works and the other doesn't even though they have the same content ...
    So what's the error message?
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    errno == 2 : No such file or directory...
    but the other prog with the same code shows output... i tried typing a new one,still the same result... what i want to say is that PROG that i created a few days ago works fine..
    when i create a new PROG even with the exact same code...it fails.. surprisingly the text copy from ur post worked fine(the one with the errno.h)...but there were no errors in my PROG... really confusing..
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    24
    Rep Power
    0
    I figured it out using the errno.h.. the problem was with the file permissions... i had to change the privileges and file permissions (windows 8) and now it is OK...
    Thank you very much .....

IMN logo majestic logo threadwatch logo seochat tools logo