Thread: program failing while trying to open/create file

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    15

    program failing while trying to open/create file

    i am opening or creating a file in the .exe's directory, depending on whether or not the file exists.

    Code:
            auto_file = fopen(path, "r+");
    i thought that if the file DOESN'T exist, then it will be created for READING AND WRITING. but if the file exists then it will open the existing file for READING AND WRITING.

    anyways, this isn't working. the program terminates from failure. what i want to do is simply create/open a file for reading and writing.

    any help???

    thanks




    i'm using this source (http://www.acm.uiuc.edu/webmonkeys/b....12.html#fopen)

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    r+ read and write text mode
    w+ read and write text mode (truncates file to zero length or creates new file)
    My guess is that you want to use "w+".
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    18
    or possibly:

    Code:
    if (!autofile)
    auto_file = fopen(path, "w+");
    else
    auto_file = fopen(path, "r+");
    how's that?

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    i just tried both, using "w+" and then waltr's code. both of them still result in the failure and termination of the program

    any ideas???

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    The "r+" mode doesn't create the file. If it exists, it opens it for reading and writing. If it doesn't exist, fopen() returns NULL.

    The "w+" mode works only slightly differently. If it exists, it truncates the file and opens it reading and writing. If it doesn't exist, the file is created and then opened for reading and writing.

    But it sounds like what you want is actually "a+". If the file exists, it's opened (but not truncated) for reading and writing. If it doesn't exist, it's created and opened for reading and writing. The only caveat is that the you'll need to reposition the stream to the beginning of the file if you want to read from the file. You can do this by simply using:

    fseek(auto_file, 0, SEEK_SET);

    ...after opening the file.

    Check here for more information.
    If you understand what you're doing, you're not learning anything.

  6. #6
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    this is still not working...here's the whole blotch of code
    Code:
        yes_or_no = fgetc(stdin);
        // get the file path of the existing/needed file
        filepath_edit(path, argv);
        
       // take the answer from above (yes_or_no) and act accordingly
        if(yes_or_no == 'y')                                 // if they already have an auto file, open it
        {
            clr_stdin(stdin);
            name_enter(str_name);                            // get the name of the file
        }
        else if(yes_or_no == 'n')
        {
                auto_file = fopen(path, "a+");
        }
    what am i doing wrong???

  7. #7
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Code:
    filepath_edit(path, argv);
    I think the problem is in here. argv is should be indexed because argv[0] is the name of your program, and that's probably what is being passed in. I also think that asking the user for a file-path is a bad idea unless you wrote an algorithm to escape all the slashes and whatnot first; that's a batch of errors waiting to happen in itself.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Actually you don't have to escape slashes if you're using a string passed from the user, because it automatically does it for you. Simply fgets some text into a buffer, with slashes in it, and print it out, you'll see what I mean.


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

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by quzah
    Actually you don't have to escape slashes if you're using a string passed from the user, because it automatically does it for you. Simply fgets some text into a buffer, with slashes in it, and print it out, you'll see what I mean.
    Ah! Of course. Occassionally I have a stupidity problem.

    But still, try passing something other than argv[0] into the filepath_edit() function.

  10. #10
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    i have it so that the file path is printed out before i go into the file opening, and the file path turns out to be perfectfly fine. everything looks like it works out.

    what else could it be??

  11. #11
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    oh, by the way i do set path = argv[0] in the function that i wrote:
    Code:
    int filepath_edit(char *path, char **argv)
    {
        int loop;
        
        path = argv[0];
    
        /* clear the .exe extension on the directory */
        for(loop = 0; loop < 256; loop++)
        {
            if(path[loop] == '\0')
            {
                while(loop > 0)
                {
                    if(path[loop] != '\\')
                        path[loop] = '\0';
                    else if(path[loop] == '\\')
                        break;
                    loop--;
                }
                break;
            }
        }
        strcpy(path+loop+1, "cars.aut");
        printf(path);
        printf("\n");
        
        return 0;
    }
    any ideas why my file input/output isnt working??

  12. #12
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
                    if(path[loop] != '\\')
                        path[loop] = '\0';
                    else if(path[loop] == '\\')
                        break;
    You don't need the second if(). It works just as well with just else.

    However,
    Code:
        for(loop = 0; loop < 256; loop++)
        {
            if(path[loop] == '\0')
            {
                while(loop > 0)
                {
                    if(path[loop] != '\\')
                        path[loop] = '\0';
                    else if(path[loop] == '\\')
                        break;
                    loop--;
                }
                break;
            }
        }
        strcpy(path+loop+1, "cars.aut");
    This whole thing could be replaced with:
    Code:
    {
      char *p;
    
      if((p = strrchr(path, '\\')))
        p++;
      else
        p = path;
    
      strcpy(p, "cars.aut");
    }
    ...and I think it makes it a little bit clearer what you're actually trying to do.
    If you understand what you're doing, you're not learning anything.

  13. #13
    Registered User
    Join Date
    Mar 2005
    Posts
    15
    whereas the code you have above is a lot cleaner, i'm pretty sure that my problem doesnt involve the path and the filename. i have printed it out on the screen (printf) and it looks fine.

    any other ideas?

  14. #14
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Well, the other thing is, if you're expecting the changes you make to path in your filepath_edit() function to be returned to the calling function then you're doing it wrong. Your filepath_edit() function is passed a copy of the pointer and then modifying that local pointer. The path variable in the calling function is unaffected.

    What you'll need to do instead is pass a pointer to a pointer to your filepath_edit() function (e.g. filepath_edit(&path)). This will change your function somewhat:
    Code:
    int filepath_edit(char **path, char **argv)
    {
      char *p;
    
      *path = argv[0];
    
      if((p = strrchr(*path, '\\')))
        p++;
      else
        p = *path;
    
      strcpy(p, "cars.aut");
      puts(*path);
    
      return 0;
    }
    Last edited by itsme86; 04-25-2006 at 12:29 PM.
    If you understand what you're doing, you're not learning anything.

  15. #15
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    Edit: ^ Definitely fix that first

    You'll probably need to re-post your code.
    Maybe all of it instead of a snippet.
    You've likely made changes.

    The only thing I see wrong with your last piece of code is if yes_or_no == 'y' you never even attempt to open a file.

    Does yes_or_no actually equal 'y' or 'n'?
    is auto_file declared correctly as a FILE pointer?
    are you sure you're looking in the right spot for the created file? (sounds like you are).

    Maybe try something simple like just opening and writing to a file.
    The actual problem may be elsewhere.
    Code:
    #include <stdio.h>
    
    int main( void )
    {
        FILE *fp;
        fp = fopen("TEST.txt", "w+");
    
        if(fp == NULL) {
            printf("Failed to open file TEST.txt\n");
            return -1;
        }
    
        fprintf(fp, "%s", "Hello World\n");
    
        fclose(fp);
    
        return 0;
    }
    Last edited by spydoor; 04-25-2006 at 11:44 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. counting program worked, but test file CRASHES IT.. WHY?
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 05-19-2002, 02:29 AM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM