Read from file into array

Discussion in 'C Programming' started by theballz@orcon.net.nz, Feb 5, 2007.

  1. Guest

    Hi,

    I am learning c programming and come across a problem i cant seem to
    solve. I have a file which i wish to parse and put certain lines
    (which do not contain a hash character) into an array and then output
    the contents of this array. The file seems to be parsed properly and
    the array gets populated but when I output the array the last line of
    my text file has filled the array. Text file and code as follows,

    Text File
    ======

    Comment 1
    Comment 2
    Comment 3
    #Comment 4
    #Comment 5

    C Code
    =====

    #include <stdio.h>


    int
    main()
    {
    FILE *myfile;
    char s[100];
    char *myarray[10][1];
    int count, count2;

    printf("Opening file for reading..\n");
    myfile = fopen("samplefile", "rs");

    if (!myfile) {
    printf("There is no file for reading...");
    return(1);
    }

    count = 0;
    printf("Parse file and filter lines into array ...\n\n");
    while (fgets(s,100,myfile))
    {
    if (!strchr(s, '#'))
    {
    myarray[count][0] = s;
    printf("Line %i passed to array: %s", count, myarray[count]
    [0]);
    count ++;
    }
    }

    fclose(myfile);

    printf("\n\nListing array contents..\n\n");
    count2 = 0;
    while (count2 < count)
    {
    printf("Line %i array value: %s", count2, myarray[count2][0]);
    count2 ++;
    }

    return (0);
    }


    When the code is run this is what I see,

    Parse file and filter lines into array ...

    Line 0 passed to array: Comment 1
    Line 1 passed to array: Comment 2
    Line 2 passed to array: Comment 3


    Listing array contents..

    Line 0 array value: #Comment 5
    Line 1 array value: #Comment 5
    Line 2 array value: #Comment 5


    No doubt it is something simple but I seem to have developed a mental
    block on this. Hope someone can sort me out.
    , Feb 5, 2007
    #1
    1. Advertising

  2. Chris Dollin Guest

    wrote:


    > I am learning c programming and come across a problem i cant seem to
    > solve. I have a file which i wish to parse and put certain lines
    > (which do not contain a hash character) into an array and then output
    > the contents of this array. The file seems to be parsed properly and
    > the array gets populated but when I output the array the last line of
    > my text file has filled the array. Text file and code as follows,


    > int
    > main()
    > {
    > FILE *myfile;
    > char s[100];
    > char *myarray[10][1];


    You have an array whose elements are pointers-to-char. (That second
    dimension appears to be pointless; what's if for?).

    > while (fgets(s,100,myfile))
    > {
    > if (!strchr(s, '#'))
    > {
    > myarray[count][0] = s;


    You assign (the address of the first element of) `s` to `myarray[count][0]`
    for several different values of `count`. But it's the /same `s`/ every
    time: every `myarray[count][0]` points to the same array, `s`.

    `s` gets overwritten with the latest (hence eventually the last) line.

    So when you print them out:

    > printf("\n\nListing array contents..\n\n");
    > count2 = 0;
    > while (count2 < count)
    > {
    > printf("Line %i array value: %s", count2, myarray[count2][0]);
    > count2 ++;
    > }


    you print the same thing - the same array, `s`, each time.

    There are different ways to fix this. The one I'd pick is to assign
    a /copy/ of `s` to `myarray[count][0]` (well, I'd cut off a dimension
    first). It's easy to write a function that mallocates space for a
    copy of its string argument, copies the string into it, and returns
    it.

    You could consider instead declaring [I'd also rename] `myarray`
    as a `char[MAXCOUNT][MAXLENGTH]` (for your choices of MAXCOUNT
    and MAXLENGTH, but naming them with an enum or #define would be
    wise; you could then declare `s` as `char s[MAXLENGTH]`). Then
    you can copy `s` directly into `myarray` with

    strcpy( myarray[count], s );

    --
    Chris "electric hedgehog" Dollin
    Nit-picking is best done among friends.
    Chris Dollin, Feb 5, 2007
    #2
    1. Advertising

  3. CBFalconer Guest

    wrote:
    >
    > I am learning c programming and come across a problem i cant seem to
    > solve. I have a file which i wish to parse and put certain lines
    > (which do not contain a hash character) into an array and then output
    > the contents of this array. The file seems to be parsed properly and
    > the array gets populated but when I output the array the last line of
    > my text file has filled the array. Text file and code as follows,


    While Chris Dollins reply is accurate, it does not train you to
    avoid such problems. You need to improve your breakdown of the
    problem. Something like:

    while (getnextlineinto(buffer)) {
    if (itisakeeper(buffer)) copyandstoreit(buffer, storage);
    }

    Now you can expand the various pseudo functions into real functions
    with parameters, and possibly expand those functions into smaller
    functions. At some point you reach a depth at which everything is
    expressed in terms the C system understands, and you are done.
    Meanwhile each function is short, and understandable.

    --
    <http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
    <http://www.securityfocus.com/columnists/423>

    "A man who is right every time is not likely to do very much."
    -- Francis Crick, co-discover of DNA
    "There is nothing more amazing than stupidity in action."
    -- Thomas Matthews
    CBFalconer, Feb 5, 2007
    #3
  4. pete Guest

    wrote:
    >
    > Hi,
    >
    > I am learning c programming and come across a problem i cant seem to
    > solve. I have a file which i wish to parse and put certain lines
    > (which do not contain a hash character) into an array and then output
    > the contents of this array. The file seems to be parsed properly and
    > the array gets populated but when I output the array the last line of
    > my text file has filled the array. Text file and code as follows,
    >
    > Text File
    > ======
    >
    > Comment 1
    > Comment 2
    > Comment 3
    > #Comment 4
    > #Comment 5
    >
    > C Code
    > =====
    >
    > #include <stdio.h>
    >
    > int
    > main()
    > {
    > FILE *myfile;
    > char s[100];
    > char *myarray[10][1];
    > int count, count2;
    >
    > printf("Opening file for reading..\n");
    > myfile = fopen("samplefile", "rs");
    >
    > if (!myfile) {
    > printf("There is no file for reading...");
    > return(1);
    > }
    >
    > count = 0;
    > printf("Parse file and filter lines into array ...\n\n");
    > while (fgets(s,100,myfile))
    > {
    > if (!strchr(s, '#'))
    > {
    > myarray[count][0] = s;
    > printf("Line %i passed to array: %s", count, myarray[count]
    > [0]);
    > count ++;
    > }
    > }
    >
    > fclose(myfile);
    >
    > printf("\n\nListing array contents..\n\n");
    > count2 = 0;
    > while (count2 < count)
    > {
    > printf("Line %i array value: %s", count2, myarray[count2][0]);
    > count2 ++;
    > }
    >
    > return (0);
    > }
    >
    > When the code is run this is what I see,
    >
    > Parse file and filter lines into array ...
    >
    > Line 0 passed to array: Comment 1
    > Line 1 passed to array: Comment 2
    > Line 2 passed to array: Comment 3
    >
    > Listing array contents..
    >
    > Line 0 array value: #Comment 5
    > Line 1 array value: #Comment 5
    > Line 2 array value: #Comment 5
    >
    > No doubt it is something simple but I seem to have developed a mental
    > block on this. Hope someone can sort me out.


    I think the problem of storing lines as strings,
    is handled better by linked list than by array.

    /* BEGIN new.c */

    #include <stdio.h>
    #include <string.h>

    #define MAXLINES 5
    #define LENGTH 99
    #define str(x) # x
    #define xstr(x) str(x)

    int main(void)
    {
    FILE *myfile;
    char s[LENGTH + 1];
    char myarray[MAXLINES][sizeof s];
    int count, count2, rc;

    puts("Opening file for reading..");
    myfile = fopen("samplefile.txt", "r");
    if (!myfile) {
    puts("There is no file for reading...");
    return 0;
    }
    count = 0;
    printf("Parse file and filter lines into array ...\n\n");
    while (count != sizeof myarray / sizeof *myarray) {
    rc = fscanf(myfile, "%" xstr(LENGTH) "[^\n]%*[^\n]", s);
    if (!feof(myfile)) {
    getc(myfile);
    }
    if (rc == 0) {
    s[0] = '\0';
    }
    if (rc == EOF) {
    break;
    }
    if (*s == '#') {
    strcpy(myarray[count], s);
    printf("Line %d passed to array: %s\n",
    count, myarray[count]);
    count ++;
    }
    }
    fclose(myfile);
    puts("\n\nListing array contents..\n");
    for (count2 = 0; count2 < count; count2++) {
    printf("Line %d array value: %s\n",
    count2, myarray[count2]);
    }
    return 0;
    }

    /* END new.c */


    --
    pete
    pete, Feb 5, 2007
    #4
  5. jaysome Guest

    On 5 Feb 2007 02:13:35 -0800, wrote:

    >Hi,
    >
    >I am learning c programming and come across a problem i cant seem to
    >solve. I have a file which i wish to parse and put certain lines
    >(which do not contain a hash character) into an array and then output
    >the contents of this array. The file seems to be parsed properly and
    >the array gets populated but when I output the array the last line of
    >my text file has filled the array. Text file and code as follows,


    While CBFalconer's reply is accurate, it does not train you to
    avoid the problem of making your readers suffer from the problem of
    not using underscores in function identifiers. He needs to improve
    his assessment of the breakdown of your problem. Something like:

    while (get_next_line_into(buffer)) {
    if (it_is_a_keeper(buffer)) copy_and_store_it(buffer, storage);
    }

    Underscores are cheap considering the benefit they provide. I've
    learned this from experience, and I have yet to find someone who
    disagrees with my assertion.

    Best regards
    --
    jay
    jaysome, Feb 6, 2007
    #5
  6. jaysome wrote:

    > While CBFalconer's reply is accurate, it does not train you to
    > avoid the problem of making your readers suffer from the problem of
    > not using underscores in function identifiers. He needs to improve
    > his assessment of the breakdown of your problem. Something like:
    >
    > while (get_next_line_into(buffer)) {
    > if (it_is_a_keeper(buffer)) copy_and_store_it(buffer, storage);
    > }
    >
    > Underscores are cheap considering the benefit they provide. I've
    > learned this from experience, and I have yet to find someone who
    > disagrees with my assertion.
    >
    > Best regards


    Case by case basis. For instance, I wouldn't use "get_line()" I would
    use "getline()" because there is no ambiguity present.
    Christopher Layne, Feb 6, 2007
    #6
  7. Chris Dollin Guest

    jaysome wrote:

    > Underscores are cheap considering the benefit they provide. I've
    > learned this from experience, and I have yet to find someone who
    > disagrees with my assertion.


    There's a first time for everything, and I am he.

    --
    Chris "electric camel" Dollin
    The "good old days" used to be much better.
    Chris Dollin, Feb 6, 2007
    #7
  8. CBFalconer Guest

    jaysome wrote:
    >
    > On 5 Feb 2007 02:13:35 -0800, wrote:
    >
    > >Hi,
    > >
    > >I am learning c programming and come across a problem i cant seem to
    > >solve. I have a file which i wish to parse and put certain lines
    > >(which do not contain a hash character) into an array and then output
    > >the contents of this array. The file seems to be parsed properly and
    > >the array gets populated but when I output the array the last line of
    > >my text file has filled the array. Text file and code as follows,

    >
    > While CBFalconer's reply is accurate, it does not train you to
    > avoid the problem of making your readers suffer from the problem of
    > not using underscores in function identifiers. He needs to improve
    > his assessment of the breakdown of your problem. Something like:
    >
    > while (get_next_line_into(buffer)) {
    > if (it_is_a_keeper(buffer)) copy_and_store_it(buffer, storage);
    > }
    >
    > Underscores are cheap considering the benefit they provide. I've
    > learned this from experience, and I have yet to find someone who
    > disagrees with my assertion.


    <g> Except that I hate finding both the shift and the _ key. The
    latter does not come naturally to the touch-typing hand. If
    anything, I prefer letting the camels into the tent.

    --
    <http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
    <http://www.securityfocus.com/columnists/423>

    "A man who is right every time is not likely to do very much."
    -- Francis Crick, co-discover of DNA
    "There is nothing more amazing than stupidity in action."
    -- Thomas Matthews
    CBFalconer, Feb 6, 2007
    #8
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. oyekomova

    Read CSV file into an array

    oyekomova, Jan 10, 2007, in forum: Python
    Replies:
    2
    Views:
    617
    Tobiah
    Jan 10, 2007
  2. Replies:
    2
    Views:
    628
    Thomas Matthews
    Feb 27, 2007
  3. Kinbote
    Replies:
    6
    Views:
    693
    Richard Heathfield
    Apr 7, 2007
  4. yogi_bear_79
    Replies:
    9
    Views:
    3,266
    yogi_bear_79
    Mar 30, 2008
  5. Alex Dowad
    Replies:
    4
    Views:
    268
    Michel Demazure
    May 1, 2010
Loading...

Share This Page