Thread: is this a safe way to deal with files?

  1. #1
    Banned
    Join Date
    Aug 2017
    Posts
    861

    is this a safe way to deal with files?

    Open file to read and write and or append to it. If not there then create it, then reopen it without closing it first. is that safe seeing how nothing yet really has been done to it.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, const char **argv)
    {
        
        if (argc < 2)
        {
            printf("no file given to open ( %s )\n", argv[argc]);
            exit(1);
        }
         char str1[10], str2[10], str3[10];
        int year;
        int count = -1;
        
        FILE *fp;
        // open user given file off cli
        fp = fopen(argv[1], "a+");
        
        if (fp == NULL)
        {   // if file not there then just create it.
            fprintf(stderr, "File not found\n");
            fp = fopen(argv[1], "w");
        } // if succesful create let user know
        if (fp != NULL)
            printf("file created\n");
        else
        {
            printf("No file\n"
                    "could not create it either\n");
            exit(1);
        }
        // now reopen for reading and appending to file <- is that the safe/ok way?
        fp = fopen(argv[1], "a+");
            
        fputs("We are in 2012", fp);
       
        rewind(fp);
        count =  fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
       
       printf("Read String1 |%s|\n", str1 );
       printf("Read String2 |%s|\n", str2 );
       printf("Read String3 |%s|\n", str3 );
       printf("Read Integer |%d|\n", year );
       printf("COUNT IS %d\n", count);
    
       fclose(fp);
    return 0;    
    }
    it worked with out any file, it created one then added to it then printed out the results with no errors

  2. #2
    Registered User
    Join Date
    Jun 2017
    Posts
    88
    a+ creates a file if the file does not exist. Only the r versions do not create a file that does not exist. (r, r+, rb+).

    Also, you still have fp open while you assign it again to another stream.

    Here are some comments I added to your code:
    Code:
    FILE *fp; // create file pointer
    fp = fopen(argv[1], "a+"); // open existing or create new file for reading and writing. set file pointer to end.
     
    if (fp == NULL) // if fopen failed
    {
        fprintf(stderr, "File not found\n");
        fp = fopen(argv[1], "w"); // delete existing file and create one with same name for writing.
    }
    if (fp != NULL)
        printf("file created\n");
    else
    {
        printf("No file\n"
            "could not create it either\n");
        exit(1);
    }
     
    fp = fopen(argv[1], "a+"); // divert fp to point to new stream.  open existing or create new file for reading and writing.  set file pointer to end.
    Last edited by jack jordan; 11-06-2017 at 12:47 PM.

  3. #3
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by jack jordan View Post
    a+ creates a file if the file does not exist. Only the r versions do not create a file that does not exist. (r, r+, rb+).

    Also, you still have fp open while you assign it again to another stream.
    ok so that check just needs to be removed because a+ automatically creates a file if not there so no need to call for it to be created and all of that other stuff I put in there, I can just remove all of that crud. .

    thanks.

  4. #4
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    90
    In case your first call to fopen() is succesfull, you make another call to fopen() while using the same FILE-pointer, thus leaving the first connection as it is, without a FILE * pointing to it.
    In your example this will work but it is good practice to first close a connection, through fclose(), in case you do not use it anymore.

  5. #5
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by ddutch View Post
    In case your first call to fopen() is succesfull, you make another call to fopen() while using the same FILE-pointer, thus leaving the first connection as it is, without a FILE * pointing to it.
    In your example this will work but it is good practice to first close a connection, through fclose(), in case you do not use it anymore.
    that what I kind of figured that it needs to be closed again to reset the pointer then (re) opened . It does strike me odd that it does not lose it so I do not see anything in the file.
    But,I got rid of that code, and now am playing around with this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>
    
    
     
    
    int main(int argc, const char **argv)
    {
        
        if (argc < 2)
        {
            printf("no file given to open ( %s )\n", argv[argc]);
            exit(1);
        }
    
        int ch; 
        
        FILE *fp;
        // open user given file off cli
        //if file not there it creates it
        fp = fopen(argv[1], "a+");
        
        if (fp == NULL)
        {   
            fprintf(stderr, "Unable to find\n"
                            "file or create one\n");
            exit(1);
             
        }  
            printf("would you like to add some words to the\n"
            "file before we get started? y/n :");
            char words[100];
            words[0] = getchar();
            if (tolower(words[0]) != 'y')
                ;
            else
            {
                printf("enter words one at a time\n"
                        "that you'd like to add\n"
                        "'q' to quit, hit enter to add word\n");
                while (words[0] != 'q')
                {
                    fgets(words, 100, stdin);
                    fputs(words,fp);                
                }
            }
        rewind(fp); // reset buffer to start reading file 
        //from begining. 
        int charcount = 0, wordcount = 0, linecount = 0;
        if (fp)
        {
            //Repeat until End Of File character is reached.    
           while ((ch=getc(fp)) != EOF) 
           {
                 // Increment character count if NOT new line or space
                if (ch != ' ' && ch != '\n')  ++charcount; 
              
              // Increment word count if new line or space character
               if (ch == ' ' || ch == '\n')  ++wordcount; 
               
              // Increment line count if new line character
               if (ch == '\n') ++linecount;
               
            }
            if (charcount > 0) 
            {
                ++linecount;
                ++wordcount;
            
            }
        }
        else
        {
            printf("file not opened\n");
            exit(1);
        }
            
        printf("Lines : %d \n", linecount);
        printf("Words : %d \n", wordcount);
        printf("Characters : %d \n", charcount);
    Last edited by userxbw; 11-06-2017 at 04:16 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to deal with conflicts in header files
    By nanodog in forum C Programming
    Replies: 6
    Last Post: 11-07-2013, 09:14 AM
  2. Deal or No Deal Proogram
    By shel5210 in forum C Programming
    Replies: 1
    Last Post: 03-28-2010, 08:04 PM
  3. Deal or No Deal listbox prob
    By kryptkat in forum Windows Programming
    Replies: 5
    Last Post: 03-30-2009, 06:53 PM
  4. Replies: 5
    Last Post: 09-18-2008, 02:57 PM

Tags for this Thread