Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Read from file into array

Reply
Thread Tools

Read from file into array

 
 
theballz@orcon.net.nz
Guest
Posts: n/a
 
      02-05-2007
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.

 
Reply With Quote
 
 
 
 
Chris Dollin
Guest
Posts: n/a
 
      02-05-2007
http://www.velocityreviews.com/forums/(E-Mail Removed) 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.

 
Reply With Quote
 
 
 
 
CBFalconer
Guest
Posts: n/a
 
      02-05-2007
(E-Mail Removed) 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


 
Reply With Quote
 
pete
Guest
Posts: n/a
 
      02-05-2007
(E-Mail Removed) 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
 
Reply With Quote
 
jaysome
Guest
Posts: n/a
 
      02-06-2007
On 5 Feb 2007 02:13:35 -0800, (E-Mail Removed) 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
 
Reply With Quote
 
Christopher Layne
Guest
Posts: n/a
 
      02-06-2007
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.
 
Reply With Quote
 
Chris Dollin
Guest
Posts: n/a
 
      02-06-2007
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.

 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      02-06-2007
jaysome wrote:
>
> On 5 Feb 2007 02:13:35 -0800, (E-Mail Removed) 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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
File.read(fname) vs. File.read(fname,File.size(fname)) Alex Dowad Ruby 4 05-01-2010 08:20 AM
read a file's line into an array, error: makes pointer from integer without a cast Kinbote C Programming 6 04-07-2007 08:50 PM
How to read from a file, stored the data in an array, and return number of records read back to main tyeung168@gmail.com C++ 2 02-27-2007 07:12 AM
Read CSV file into an array oyekomova Python 2 01-10-2007 08:09 PM
Need to concatenate all files in a dir together into one file and read the first 225 characters from each file into another file. Tony Perl Misc 5 04-19-2004 03:28 PM



Advertisments