473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Read from file into array

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 '07 #1
7 3563
th******@orcon.net.nz 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.

Feb 5 '07 #2
th******@orcon.net.nz 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
Feb 5 '07 #3
th******@orcon.net.nz 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
Feb 5 '07 #4
On 5 Feb 2007 02:13:35 -0800, th******@orcon.net.nz 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
Feb 6 '07 #5
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.
Feb 6 '07 #6
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.

Feb 6 '07 #7
jaysome wrote:
>
On 5 Feb 2007 02:13:35 -0800, th******@orcon.net.nz 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.
<gExcept 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

Feb 6 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Chris | last post by:
Can anybody help. I need to read a txt file backwords line by line. Can anybody help me do this. Thanks Chris
5
by: deko | last post by:
I have a text file ("eighty.txt") that looks like this: 83|84|85|86 I can read the file into an array like this: $numbers= file("eighty.txt"); But how do I key the array? I'd like to use...
3
by: deko | last post by:
It's nice to be able to generate an html table from a PHP array. I know how to do this, but the array in question is built from a file. The file in question can be very long, and I only want the...
3
by: Wei-Chao Hsu | last post by:
There are some data files look like 1.) data1.txt ---------------- 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 2.) data2.txt
9
by: Adi | last post by:
Hello eveyone, I wanna ask a very simple question here (as it was quite disturbing me for a long time.) My problem is to read a file line by line. I've tried following implementations but still...
9
by: srikanth | last post by:
i have a text file like below, test.txt file (actually my test file file is with 10000 lines but here i tested with 3 lines) 3 06.09.2006 16:37:25 3 06.09.2006 16:40:02 3 06.09.2006 16:42:31...
14
by: chance | last post by:
Hello, I have a file on disk called TEMP.ZIP and I would like to somehow get this into a memory stream so I can eventually do this: row = dataStream.ToArray() However, I am not sure of the...
5
by: runsun | last post by:
Thanks in advance. This program is written in C. It needs to read all characters from a file; then write them into a 3D array (yes, 3D!). The file is a .prn file (one of the Excel types), which...
13
by: rohit | last post by:
Hi All, I am new to C language.I want to read integers from a text file and want to do some operation in the main program.To be more specific I need to multiply each of these integers with another...
5
by: dm3281 | last post by:
Hello, I have a text report from a mainframe that I need to parse. The report has about a 2580 byte header that contains binary information (garbage for the most part); although there are a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.