Thread: File management, help please!

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    16

    File management, help please!

    Hi, Im dealing with file management now, and I need some help here. Well what I need is to get the first integer from a file and assign it to a variable and the others integers to an array. Example

    Thats my file content 5 4 6 7 8 0 and that would be the code:

    Code:
    struct Array{
        int n;
        int *v;
    };
    struct Array ArrayCreaFichero(FILE * f){
    
    
    struct Array array1;
    f = fopen("array.txt","r");
    array1.n = 5 (the first value taken from the file)
    array1.v = [4,6,7,8,0](the rest of values taken from the file)

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The good way to read data from a file, into a variable or an array, depends on the way the data is arranged. All the details are important.

    Post an example of the file your program is to read data from, (just a half dozen lines should be enough), and show what you've done to try and make it work. Then we know we're on the same page.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If you know the format of the file is consistent with text values, then you could use fscanf. If not, then you could use fgets.
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    May 2013
    Posts
    16
    Quote Originally Posted by Adak View Post
    The good way to read data from a file, into a variable or an array, depends on the way the data is arranged. All the details are important.

    Post an example of the file your program is to read data from, (just a half dozen lines should be enough), and show what you've done to try and make it work. Then we know we're on the same page.
    The file would be a .txt and it would be like this:

    37 4 5 6 3 2 1 6 9 0 1 3 4 5 6 8 1 8
    3 4 5 1 3 8 2 4 2 2 8 1 8 3 4 8 2 8

    The first value would be the size of the array. What did I do? just what I posted, nothing more because I have no idea what function I have to use to get one value (the first one here)

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Code:
        fscanf(f, "%d", &some_int);
    reads the value of a single int from f, and stores it in some_int. If it fails, fscanf() returns a value other than one (since it is attempting to read one value) in this case.

    Then
    Code:
        array1.v = malloc(array1.n * sizeof(*array1.v));
    will cause array1.v to point at the first element of a dynamically allocated array of (array1.n) integers. Just remember that malloc() returns NULL if it fails.

    You should be able to work out a solution from those bits of information.

    Side note (anticipating other things that can go wrong): Just remember that malloc() requires an #include <stdlib.h> to be in effect (otherwise "array1.v = malloc(...);" won't compile. If you have #include'd <stdlib.h> and the compiler still complains, that means your compiler is a C++ compiler rather than a C compiler.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Logic like this worked OK.

    Code:
       if(!fp) {
          printf("Error opening data.txt file!\n");
          return 1;
       }
       i=fscanf(fp, "%d", &numdigits);
       if(i==1) {
          digits = malloc(numdigits * sizeof(int));
          if(!digits) {
             printf("Error allocating memory!\n");
             return 1;
          }
          for(i=0;i<numdigits;i++) {
             fscanf(fp, "%d", &digits[i]);
             printf("%d ",digits[i]);
          }
    
       }
    Add in the other parts, and you should be off and running.

  7. #7
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Adak: Perhaps it might be better to abort in all error cases, just like the code does if the file cannot be opened? And maybe add some comments, too?

    Say,
    Code:
        /* Verify the file was opened. */
        if (!fp) {
            printf("Error opening data.txt file!\n");
            return 1;
        }
    
        /* Read the number count from the file. */
        if (fscanf(fp, "%d", &numdigits) != 1) {
            printf("Cannot read the number count from data.txt!\n");
            return 1;
        }
        if (numdigits < 1) {
            printf("The number count in data.txt was too small!\n");
            return 1;
        }
    
        /* Allocate memory for numdigits integer numbers. */
        digits = malloc(numdigits * sizeof *digits);
        if (!digits) {
            printf("Out of memory (asked for %d numbers).\n");
            return 1;
        }
    
        /* Read numdigits integers into the allocated array. */
        for (i = 0; i < numdigits; i++) {
            if (fscanf(fp, "%d", &digits[i]) != 1) {
                printf("Error reading number %d of %d from data.txt!\n", i + 1, numdigits);
                return 1;
            }
    
            /* Print the read number to standard output. */
            printf("%d\n", digits[i]);
        }
    Or is this actually going too far? It is almost all the necessary code..

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Your line 20 exhibits undefined behaviour, Nominal. Not good form when attempting to print an error message.

    It's usually a good idea to write error messages to stderr, too.

    You're structured the code so it tests for failure, whereas I'd assume failure is the default condition, and test for success. That may seem backward, but it can often result in more concise code that needs less comments.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by grumpy View Post
    Your line 20 exhibits undefined behaviour, Nominal.
    Good catch, thanks! Obviously, that should have been
    Code:
        printf("Out of memory (asked for %d numbers).\n", numdigits);
    but the stuff after the comma was lost somewhere. And I'm too late to edit it now. Ouch.

    Quote Originally Posted by grumpy View Post
    It's usually a good idea to write error messages to stderr, too.
    Fully agreed. For the file open case, I'd personally recommend
    Code:
    if (!fp) {
        fprintf(stderr, "Cannot open data.txt: %s.\n", strerror(errno));
        return 1;
    }
    because fopen() sets errno based on the reason for the failure when it fails. (That requires two more additional includes, <string.h> and <errno.h>.) This way, if the open fails, the user sees also why it failed.

    Quote Originally Posted by grumpy View Post
    You're structured the code so it tests for failure, whereas I'd assume failure is the default condition, and test for success. That may seem backward, but it can often result in more concise code that needs less comments.
    Here, the four points (plus the fifth point inside the loop) are basically fatal, there not being any obvious way to deal with the error.

    I thought it would be easier for a new programmer to understand the checks, if they are done immediately and in sequence. Also, minimum changes to Adak's example. (As to comments, I know they're not spot on, but I did try to describe the intent, not the actions the code does.)

    The way I'd personally develop the exercise further would be to move all this into a function, then adding the necessary error cleanup to avoid leaking memory or file handles in error cases. In that case, your structure is definitely better, as the cleanups are nicely ordered, and nested at the same depth as the corresponding open or allocation. You can add the cleanups to the code I showed, too, but it wouldn't be as concise.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. file management in c help
    By coklat91 in forum C Programming
    Replies: 1
    Last Post: 12-19-2011, 09:23 PM
  2. file management in c
    By Animesh Gaitond in forum C Programming
    Replies: 4
    Last Post: 09-20-2011, 10:28 AM
  3. CodeBlocks IDE file management
    By ~Kyo~ in forum Windows Programming
    Replies: 3
    Last Post: 02-08-2011, 11:23 AM
  4. File Management in C
    By Figen in forum C Programming
    Replies: 6
    Last Post: 01-31-2011, 03:14 PM
  5. need help for file management
    By edesign in forum C Programming
    Replies: 5
    Last Post: 02-08-2008, 11:29 PM