473,608 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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("samplefi le", "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,my file))
{
if (!strchr(s, '#'))
{
myarray[count][0] = s;
printf("Line %i passed to array: %s", count, myarray[count]
[0]);
count ++;
}
}

fclose(myfile);

printf("\n\nLis ting 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 3583
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,my file))
{
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\nLis ting 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 (getnextlineint o(buffer)) {
if (itisakeeper(bu ffer)) 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.securityfoc us.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("samplefi le", "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,my file))
{
if (!strchr(s, '#'))
{
myarray[count][0] = s;
printf("Line %i passed to array: %s", count, myarray[count]
[0]);
count ++;
}
}

fclose(myfile);

printf("\n\nLis ting 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("samplefi le.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\nListi ng 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.securityfoc us.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
17066
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
3494
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 strings as keys: three, four, five, six - do I add the key names in the file?
3
7954
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 first 10 lines. So, I'd like to reduce the overhead it takes to read the file into the array by limiting the number of lines read in - rather than have the entire file read in and then limiting the output to the html table. $visits=...
3
4396
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
5200
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 facing problems: Assume that FILE* filePointer; unsigned char lineBuffer;
9
2013
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 i want to read this and output as it looks but iam getting abnormal
14
11626
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 correct way to get it into a memory stream. Any help appreciated.
5
5675
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 separates columns with space. To simplify the question, the file contains 3 rows and 2 columns: abc 2,3 defg 4 h 5,6 array is array, where the 3rd D contains the # of rows; 2nd D has #conlumns; 1st D contains the character elements. i.e....
13
10391
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 set of integers stored in an array.It would be a great help if you could provide some code for it.I tried the function fscanf but by that I am able to read only the first integer of the text file.Please help me.
5
11244
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 couple areas that have ASCII text that I need to extract. At the end of the 2580 bytes, I can read the report like a standard text file. It should have CR/LF at the end of each line. What is the best way for me to read this report using C#. It is...
0
8495
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8470
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8330
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6011
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5475
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3960
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4023
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1328
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.