Read from file into array

T

theballz

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.
 
C

Chris Dollin

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 );
 
C

CBFalconer

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
 
P

pete

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 */
 
J

jaysome

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
 
C

Christopher Layne

jaysome said:
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.
 
C

Chris Dollin

jaysome said:
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.
 
C

CBFalconer

jaysome said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top