problem opening a file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • aldrin@xtra.co.nz

    problem opening a file

    I'm trying to run this code under windows xp sp2 using codeblocks v1.0
    compiler with great difficulty.Ther e is no problem with running this
    under KDevelop in linux. Any help would be greatly appreciated.


    Enter an interesting string.
    Too many cooks spoil the broth
    Error opening C:\myfile.txt for writing. Program termnated.
    This application has requested the Runtime to terminate it in an
    unusual way.
    Please contact the application's support team for more information.

    Press ENTER to continue.
    *************** *************** *************** *************** *************** ******
    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
    char mystring[80];
    int i = 0;
    int lstr = 0;
    int mychar = 0;
    FILE *pfile = NULL;
    char *filename = "C:\\myfile.txt ";

    printf("\nEnter an interesting string.\n");
    gets(mystring);

    pfile = fopen(filename, "w");
    if(pfile == NULL)
    {
    printf("Error opening %s for writing. Program termnated.",
    filename);
    abort();
    }

    lstr = strlen(mystring );
    for(i=lstr -1; i >= 0; i--)
    fputc(mystring[i], pfile);

    fclose(pfile);

    /*ope file for reading*/
    pfile = fopen(filename, "r");
    if(pfile == NULL)
    {
    printf("Error opening %s for reading. Program terminated.",
    filename);
    abort();
    }

    /*Read a character from the file and display it*/
    while((mychar = fgetc(pfile)) != EOF)
    putchar(mychar) ;
    putchar('\n');

    fclose(pfile);
    remove(filename );

    return 0;
    }

  • Mike Wahler

    #2
    Re: problem opening a file


    <aldrin@xtra.co .nz> wrote in message
    news:1139704997 .964354.32630@f 14g2000cwb.goog legroups.com...[color=blue]
    > I'm trying to run this code under windows xp sp2 using codeblocks v1.0
    > compiler with great difficulty.Ther e is no problem with running this
    > under KDevelop in linux. Any help would be greatly appreciated.
    >
    >
    > Enter an interesting string.
    > Too many cooks spoil the broth
    > Error opening C:\myfile.txt for writing. Program termnated.
    > This application has requested the Runtime to terminate it in an
    > unusual way.
    > Please contact the application's support team for more information.[/color]

    I don't see anything wrong with the code (other than the
    use of the inherently dangerous 'gets()' function).

    For some reason, the host system has refused to open your
    output file. C can only tell you if the operation succeeded
    or not, but not *why* it didn't succeed.

    Some possible reasons for 'fopen()' to fail on Windows:
    1. Disk is full
    2. Disk failure
    3. Insufficient access rights.
    4. Disk is inaccessible (e.g. disconnected from a network)
    5. File is already opened by another process, but not 'shared'.

    How to deal with any of these issues (or others) is not
    covered by the C language.

    The message about 'terminate in an unusual way' reflects the
    fact that you called the standard function 'abort()', which
    is indeed not the 'normal' way to terminate a C program.
    The 'normal' way is to have function 'main()' return control
    to the host system. (Also see 'exit()')

    -Mike


    Comment

    • Walter Roberson

      #3
      Re: problem opening a file

      In article <1139704997.964 354.32630@f14g2 000cwb.googlegr oups.com>,
      <aldrin@xtra.co .nz> wrote:[color=blue]
      >I'm trying to run this code under windows xp sp2 using codeblocks v1.0
      >compiler with great difficulty.Ther e is no problem with running this
      >under KDevelop in linux. Any help would be greatly appreciated.[/color]
      [color=blue]
      >Enter an interesting string.
      >Too many cooks spoil the broth
      >Error opening C:\myfile.txt for writing. Program termnated.
      >This application has requested the Runtime to terminate it in an
      >unusual way.[/color]
      [color=blue]
      > char *filename = "C:\\myfile.txt ";[/color]
      [color=blue]
      > pfile = fopen(filename, "w");
      > if(pfile == NULL)
      > {
      > printf("Error opening %s for writing. Program termnated.",
      >filename);
      > abort();
      > }[/color]

      The rest of the program does not matter, as it is clear that in
      the fault case the abort() is what is terminating the program.

      So you have a situation where under true windows, C:\myfile.txt
      cannot be opened for writing, but under an emulator (?),
      KDevelop in linux, it can be.

      My guess would be that in the real windows XP system, your process
      does not have authorization to create files directly in C:\
      and that in KDevelop either there is no file permission testing
      or else that the emulated C:\ is a directory that you happen to
      have access to.

      I would suggest replacing the printf() with perror() as that will
      print out the error reason. perror() does not support %s formats
      though, so either work around that or include <errno.h> and
      use strerror().
      --
      All is vanity. -- Ecclesiastes

      Comment

      • Keith Thompson

        #4
        Re: problem opening a file

        aldrin@xtra.co. nz writes:[color=blue]
        > I'm trying to run this code under windows xp sp2 using codeblocks v1.0
        > compiler with great difficulty.Ther e is no problem with running this
        > under KDevelop in linux. Any help would be greatly appreciated.[/color]

        I have no idea what "codeblocks " is, but if your problem actually
        depends on that, then it's not something we can help you with here.
        [color=blue]
        > Enter an interesting string.
        > Too many cooks spoil the broth
        > Error opening C:\myfile.txt for writing. Program termnated.
        > This application has requested the Runtime to terminate it in an
        > unusual way.
        > Please contact the application's support team for more information.
        >
        > Press ENTER to continue.[/color]

        I don't see any serious problems that would necessarily explain the
        symptoms you're seeing. I do see some serious problems, though.

        The "This application has requested ..." message is presumably caused
        by the call to abort(). There's no need to terminate the program so
        drastically; exit(EXIT_FAILU RE) is just fine.

        Error messages are normally printed to stdout, not stderr (but that's
        not required).
        [color=blue]
        > #include <stdio.h>
        > #include <stdlib.h>
        >
        > int main()
        > {
        > char mystring[80];
        > int i = 0;
        > int lstr = 0;
        > int mychar = 0;
        > FILE *pfile = NULL;
        > char *filename = "C:\\myfile.txt ";[/color]

        Obviously this file name is non-portable. On Linux, your program
        would probably create a file in the current directory whose name is
        C:\myfile.txt
        Check whether that's a valid file name in the environment in which
        your program runs. Do you have write permission on C:\? What happens
        if you change the file name to just "myfile.txt " (i.e., create it in
        the current directory)?

        Note that any considerations about directories, path names, and the
        meaning of a file name is system-specific. If you're still having
        trouble, you might try a system-specific newsgroup.
        [color=blue]
        > printf("\nEnter an interesting string.\n");
        > gets(mystring);[/color]

        Never use gets(). Never. Never ever. For all practical purposes, it
        *cannot* be used safely. (There are obscure circumstances in which it
        can be used safely, but if you know enough to figure that out you know
        enough not to use gets() anyway.)

        See <http://www.c-faq.com/stdio/getsvsfgets.htm l>.
        [color=blue]
        > pfile = fopen(filename, "w");
        > if(pfile == NULL)
        > {
        > printf("Error opening %s for writing. Program termnated.",
        > filename);[/color]

        On some systems, a failing fopen() *might* set a meaningful value for
        errno. Try setting errno to 0 before the fopen() call, and checking
        its value after the call; use perror() to print an error message
        *only* if errno!=0. The result may or may not be meaningful (the
        standard doesn't say anything about fopen()'s effect on errno). See
        also <http://www.c-faq.com/misc/errno.html>.
        [color=blue]
        > abort();
        > }
        >
        > lstr = strlen(mystring );[/color]

        You use strlen(), but you don't have a "#include <string.h>". Turn up
        the warning level on your compiler; it should be able to warn you
        about this kind of thing.
        [color=blue]
        > for(i=lstr -1; i >= 0; i--)
        > fputc(mystring[i], pfile);
        >
        > fclose(pfile);[/color]

        You've just created a text file that isn't terminated by a new-line
        character. Some implementations might require a new-line at the end
        of every text file. (Yours probably doesn't, but if you care about
        portability you should make sure it's there anyway).
        [color=blue]
        > /*ope file for reading*/
        > pfile = fopen(filename, "r");
        > if(pfile == NULL)
        > {
        > printf("Error opening %s for reading. Program terminated.",
        > filename);
        > abort();
        > }
        >
        > /*Read a character from the file and display it*/
        > while((mychar = fgetc(pfile)) != EOF)
        > putchar(mychar) ;
        > putchar('\n');
        >
        > fclose(pfile);
        > remove(filename );[/color]

        Misleading indentation. Only the "putchar(mychar );" is part of the
        while loop. With correct indentation:

        while((mychar = fgetc(pfile)) != EOF)
        putchar(mychar) ;
        putchar('\n');

        fclose(pfile);
        remove(filename );

        Personally, I always use braces with control structures, even when
        they're not required, so I'd write it as:

        while((mychar = fgetc(pfile)) != EOF) {
        putchar(mychar) ;
        }
        putchar('\n');

        fclose(pfile);
        remove(filename );
        [color=blue]
        > return 0;
        > }[/color]

        Since you're having a problem on the initial fopen() call, the rest of
        your program isn't relevant to the problem. You could have narrowed
        your program down to something much smaller before posting.

        (The program uses a temporary file to reverse a string. I'm sure
        you're aware that there are much easier ways to reverse a string.)

        --
        Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
        San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
        We must do something. This is something. Therefore, we must do this.

        Comment

        • Aldrin Fabricius

          #5
          Re: problem opening a file

          >I would suggest replacing the printf() with perror() as that will[color=blue]
          >print out the error reason. perror() does not support %s formats
          >though, so either work around that or include <errno.h> and
          >use strerror().[/color]

          I'll try the suggestions above and see how it goes. Thanks!

          Comment

          • Aldrin Fabricius

            #6
            Re: problem opening a file

            Keith great advice!! In my excitement to post i forgot to mention that
            i modified the code to point to /home/user/text.txt.
            [color=blue]
            >Never use gets(). Never. Never ever. For all practical purposes, it
            >*cannot* be used safely. (There are obscure circumstances in which it
            >can be used safely, but if you know enough to figure that out you know
            >enough not to use gets() anyway.)[/color]

            Ignorance is bliss!! I will go back to the drawing board atleast with
            something to think about. Thanks for that.

            Comment

            • Aldrin Fabricius

              #7
              Re: problem opening a file

              >Some possible reasons for 'fopen()' to fail on Windows:[color=blue]
              >1. Disk is full
              >2. Disk failure
              >3. Insufficient access rights.
              >4. Disk is inaccessible (e.g. disconnected from a network)
              >5. File is already opened by another process, but not 'shared'.[/color]

              Double checked all disk/s have plenty of space with the same error
              popping up under different IDEs(Visual C++ .net, Dev C++)on more than
              one PC, and using admin account didn't have any effect. Also tested on
              PCs running locally without networking and couldn't really see anything
              that couldve interfered with the file opening other than the shoddy
              coding.
              [color=blue]
              > The 'normal' way is to have function 'main()' return control
              >to the host system. (Also see 'exit()')[/color]
              thanks for that advice taken.

              Comment

              • Kenneth Brody

                #8
                Re: problem opening a file

                aldrin@xtra.co. nz wrote:
                [...][color=blue]
                > Error opening C:\myfile.txt for writing. Program termnated.[/color]
                [...][color=blue]
                > pfile = fopen(filename, "w");
                > if(pfile == NULL)
                > {
                > printf("Error opening %s for writing. Program termnated.",
                > filename);[/color]

                Try changing the above to:

                perror(filename );

                Although, as I understand it, the standard does not require fopen() to
                set errno, your system probably does, so the above will probably print
                the filename and the reason for the failure.

                If, for some reason, your system doesn't set errno, then you'll have to
                do some further investigation to find the cause.
                [color=blue]
                > abort();
                > }[/color]
                [...]


                --
                +-------------------------+--------------------+-----------------------------+
                | Kenneth J. Brody | www.hvcomputer.com | |
                | kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
                +-------------------------+--------------------+-----------------------------+
                Don't e-mail me at: <mailto:ThisIsA SpamTrap@gmail. com>


                Comment

                • Kenneth Brody

                  #9
                  Re: problem opening a file

                  Walter Roberson wrote:
                  [...][color=blue]
                  > So you have a situation where under true windows, C:\myfile.txt
                  > cannot be opened for writing, but under an emulator (?),
                  > KDevelop in linux, it can be.[/color]
                  [...]

                  FYI -- "C:\myfile. txt" is a valid filename under Linux, so there may not
                  be any emulator involved. (Why anyone would want such a filename under
                  Linux is a separate issue.)

                  --
                  +-------------------------+--------------------+-----------------------------+
                  | Kenneth J. Brody | www.hvcomputer.com | |
                  | kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
                  +-------------------------+--------------------+-----------------------------+
                  Don't e-mail me at: <mailto:ThisIsA SpamTrap@gmail. com>

                  Comment

                  • CBFalconer

                    #10
                    Re: problem opening a file

                    Kenneth Brody wrote:[color=blue]
                    > Walter Roberson wrote:
                    > [...][color=green]
                    > > So you have a situation where under true windows, C:\myfile.txt
                    > > cannot be opened for writing, but under an emulator (?),
                    > > KDevelop in linux, it can be.[/color]
                    > [...]
                    >
                    > FYI -- "C:\myfile. txt" is a valid filename under Linux, so there
                    > may not be any emulator involved. (Why anyone would want such a
                    > filename under Linux is a separate issue.)[/color]

                    Is an escaped m a legitimate string character? I could understand
                    your statement about "C:\noxious.txt ", "C:\bullturd.tx t", or
                    "C:\ambivalent. txt". Use of "C:\truncate.tx t" is likely to cause
                    future difficulties.

                    --
                    "If you want to post a followup via groups.google.c om, don't use
                    the broken "Reply" link at the bottom of the article. Click on
                    "show options" at the top of the article, then click on the
                    "Reply" at the bottom of the article headers." - Keith Thompson
                    More details at: <http://cfaj.freeshell. org/google/>
                    Also see <http://www.safalra.com/special/googlegroupsrep ly/>


                    Comment

                    • Keith Thompson

                      #11
                      Re: problem opening a file

                      CBFalconer <cbfalconer@yah oo.com> writes:[color=blue]
                      > Kenneth Brody wrote:[color=green]
                      >> Walter Roberson wrote:
                      >> [...][color=darkred]
                      >> > So you have a situation where under true windows, C:\myfile.txt
                      >> > cannot be opened for writing, but under an emulator (?),
                      >> > KDevelop in linux, it can be.[/color]
                      >> [...]
                      >>
                      >> FYI -- "C:\myfile. txt" is a valid filename under Linux, so there
                      >> may not be any emulator involved. (Why anyone would want such a
                      >> filename under Linux is a separate issue.)[/color]
                      >
                      > Is an escaped m a legitimate string character? I could understand
                      > your statement about "C:\noxious.txt ", "C:\bullturd.tx t", or
                      > "C:\ambivalent. txt". Use of "C:\truncate.tx t" is likely to cause
                      > future difficulties.[/color]

                      No, "\m" is not legal in a C string literal, but the original program
                      had "C:\\myfile.txt "; since then, I think we've been using
                      "C:\myfile.txt" , not interpreted as a C string literal, to refer to
                      the name.

                      --
                      Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                      San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                      We must do something. This is something. Therefore, we must do this.

                      Comment

                      • Lew Pitcher

                        #12
                        Re: problem opening a file

                        -----BEGIN PGP SIGNED MESSAGE-----
                        Hash: SHA1

                        CBFalconer wrote:[color=blue]
                        > Kenneth Brody wrote:[color=green]
                        >> Walter Roberson wrote:
                        >> [...][color=darkred]
                        >>> So you have a situation where under true windows, C:\myfile.txt
                        >>> cannot be opened for writing, but under an emulator (?),
                        >>> KDevelop in linux, it can be.[/color]
                        >> [...]
                        >>
                        >> FYI -- "C:\myfile. txt" is a valid filename under Linux, so there
                        >> may not be any emulator involved. (Why anyone would want such a
                        >> filename under Linux is a separate issue.)[/color]
                        >
                        > Is an escaped m a legitimate string character?[/color]

                        FWIW, the OP's code didn't escape the 'm' of "myfile". Instead, it included an
                        escape for the '\'

                        OP> char *filename = "C:\\myfile.txt ";
                        ...
                        OP> pfile = fopen(filename, "w");
                        ...
                        OP> printf("Error opening %s for writing. Program termnated.",fil ename);

                        I believe that Kenneth's comment was made wrt the final filename, after the
                        escape sequence had been resolved.

                        [snip]

                        - --
                        Lew Pitcher

                        Master Codewright & JOAT-in-training | GPG public key available on request
                        Registered Linux User #112576 (http://counter.li.org/)
                        Slackware - Because I know what I'm doing.
                        -----BEGIN PGP SIGNATURE-----
                        Version: GnuPG v1.2.7 (GNU/Linux)

                        iD8DBQFD77pVagV FX4UWr64RAgt6AK DnRp2GcgGKZKHTt 75XtrKMcDU6wwCf T3+M
                        PX6cVxun332I01e Y75Z2tic=
                        =MoEH
                        -----END PGP SIGNATURE-----

                        Comment

                        Working...