473,769 Members | 7,923 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading data from a file into a 2d array

Okay, this if my first post so go easy on me plus I've only been using
C for a couple of weeks. I'm working on a program currently that
requires me to read data from a .dat file into a 2d array and then
print out the contents of the 2d array to the screen. I wil also need
to append data to the .dat file but mostly right now I'm worrying about
getting the info into the 2d array. My .dat file looks like this

1 20000
2 30000
3 40000

etc. The first number standing for an ID and the second standing for a
weight.

#include <stdio.h>
main()
{
FILE *pRead;
int array[20][3];
pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("\nFile cannot be opened\n");

else
printf("\nConte nts of test.dat\n\n");
fscanf(pRead,"% s,%s", array);

while ( !feof(pRead) )
{
printf("%s%s\n" , array);
fscanf(pRead, "%s,%s", array);
}

}

I know I need to use a for loop or something to that idea so that I can
read in the column and then the row. I'm really drawing a blank here on
how to get that working. Could someone point me in the right direction?
Cause right now my output is coming out like this :

11
20002000
22
30003000

etc.
Also, if I use %d instead of %s here, I get segmentation faults. Can
anyone explain why this is happening? Thanks.

Feb 23 '06 #1
29 10433
do you mind telling me why you used a multi-dimintinal array? to me it
seems also you are
using an integer array and filling it with strings?

Feb 23 '06 #2
da*********@gma il.com writes:
do you mind telling me why you used a multi-dimintinal array? to me it
seems also you are
using an integer array and filling it with strings?


Please read <http://cfaj.freeshell. org/google/>. Thanks.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 23 '06 #3
On 2006-02-23, yourmycaffiene <dd****@gmail.c om> wrote:
Okay, this if my first post so go easy on me plus I've only been using
C for a couple of weeks. I'm working on a program currently that
requires me to read data from a .dat file into a 2d array and then
print out the contents of the 2d array to the screen. I wil also need
to append data to the .dat file but mostly right now I'm worrying about
getting the info into the 2d array. My .dat file looks like this

1 20000
2 30000
3 40000

etc. The first number standing for an ID and the second standing for a
weight.

#include <stdio.h>
main()
{
FILE *pRead;
int array[20][3];
pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("\nFile cannot be opened\n");

else
printf("\nConte nts of test.dat\n\n");
fscanf(pRead,"% s,%s", array);

while ( !feof(pRead) )
{
printf("%s%s\n" , array);
fscanf(pRead, "%s,%s", array);
}

}

I know I need to use a for loop or something to that idea so that I can
read in the column and then the row. I'm really drawing a blank here on
how to get that working. Could someone point me in the right direction?
Cause right now my output is coming out like this :

11
20002000
22
30003000

etc.
Also, if I use %d instead of %s here, I get segmentation faults. Can
anyone explain why this is happening? Thanks.


Have a look at this code and work from there:

#include <stdio.h>
main()
{

unsigned long a,b;

FILE * pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("File cannot be opened\n");

else
printf("Content s of test.dat : \n");

while ( !feof(pRead) ){
fscanf(pRead,"% u %u\n", &a,&b);
printf("%u %u\n",a,b);
}

}
Some pointers to help you on the way : fcanf can do the conversions
for you : use it if you use fscanf. You were reading in strings and
then storing them in "int" storage - this is naughty and very
unclean. Try to get a handle on the types and keep them
concistent. While C can and does allow you to stick data in the wrong
"type memory" it is a very bad idea.

The storage in the array we leave as an excercise :)

--
Remove evomer to reply
Feb 23 '06 #4
yourmycaffiene wrote:
Okay, this if my first post so go easy on me plus I've only been using
C for a couple of weeks. I'm working on a program currently that
requires me to read data from a .dat file into a 2d array and then
print out the contents of the 2d array to the screen. I wil also need
to append data to the .dat file but mostly right now I'm worrying about
getting the info into the 2d array. My .dat file looks like this

1 20000
2 30000
3 40000

etc. The first number standing for an ID and the second standing for a
weight.

#include <stdio.h>
Vertical space is cheap...
main()
Better spell it out:

int main(void)
{
FILE *pRead;
int array[20][3];
Why 3 as a second dimension if you only have two columns. Avoiding
zero-based indexing in this way is a waste of memory. Imagine if the
first dimension was 200,000.
pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("\nFile cannot be opened\n");
Vertical space here hinders reading...

You also probably want to abort execution at this point. The way it
stands, you'll still try to read from the file you failed to open.
else
printf("\nConte nts of test.dat\n\n");
Apart from lack of vertical spacing, you should really indent properly.
E.g.:

else
printf("Blah.\n ");
fscanf(pRead,"% s,%s", array);
Quite a few problems here. You're specifying `%s` which expects a
string from the file, but you tell `fscanf` to put it into a
two-dimensional array of `int`s. Apart from failing to do what you
want, along that path lies the monster of buffer overflows. You also
tell `fscanf` to expect two strings, but pass only one address of a
variable to store them in.

BTW, what was wrong with including the above line into `while` loop? As
it stands, you'd have to guarantee the file is not empty (impossible).
Also, if you can guarantee that, a `do` loop would have been clearer.
while ( !feof(pRead) )
{
printf("%s%s\n" , array);
Now you're trying to print contents of an array of `int`s as a string.
Also, you're telling `printf` to expect two strings, but only pass it
one pointer (of the wrong type, as well).
fscanf(pRead, "%s,%s", array);
Same comment as for the similar line above. Plus, You should really
have swapped the above two (or dropped this one, and put the first one
like this in the loop).
}
You should close the file as well:

fclose(pFile);

C99 will let you omit final `return 0;` but it's good practice to spell
things out.

return 0;
}
This is probably what you want:

#include <stdio.h>
#include <stdlib.h>

#define DAT_MAX_LINES 20

int main(void)
{
int array[DAT_MAX_LINES][2];
int n = 0;
int i;

FILE * pRead = fopen("test.dat ", "r");

if (!pRead)
{
printf("File cannot be opened\n");
return EXIT_FAILURE;
}

printf("Content s of test.dat:\n");

while ( (n < DAT_MAX_LINES) && (!feof(pRead)) )
{
fscanf(pRead,"% d%d\n", &array[n][0], &array[n][1]);
++n;
}

if ( (!feof(pFile)) && (n == DAT_MAX_FILES) )
{
printf("Error: file to large for array.\n");
}

fclose(pFile);

for (i = 0; i < n; ++i)
{
printf("%d: %d, %d\n", i, array[i][0], array[i][1]);
}

return EXIT_SUCCESS;
}

<snip>
Also, if I use %d instead of %s here, I get segmentation faults. Can
anyone explain why this is happening? Thanks.


See comment above about matching the formats and the parameters (and
the number of the latter). Your compiler should have warned you about
these (mine did). Turn up the warining level as high as you can.

--
BR, Vladimir

Feb 23 '06 #5
On Thu, 23 Feb 2006 08:48:59 +0000, Richard G. Riley wrote:
Have a look at this code and work from there:

#include <stdio.h>
main()
{

unsigned long a,b;

FILE * pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("File cannot be opened\n");

else
printf("Content s of test.dat : \n");

while ( !feof(pRead) ){
fscanf(pRead,"% u %u\n", &a,&b);
printf("%u %u\n",a,b);
}

}


This is a dodgy pattern to recommend. You get, I think, undefined
behaviour if you test a NULL FILE * with feof (I get a core dump rather
than any flying demons -- YMMV). You definitely get UB if you test for
end-of-file before reading anything (because there may be no data to read)
and your input is very sensitive to the format used (not technically a
problem, of course, but a beginenr will be baffled by the change in
behaviour caused by switching to "%u %u" from "%u %u\n").

I think the following is more beginner-friendly:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
unsigned long a, b;
FILE *pRead = fopen("test.dat ", "r");

if (pRead == NULL)
printf("File cannot be opened\n");
else {
printf("Content s of test.dat : \n");

while (fscanf(pRead," %u %u", &a,&b) == 2)
printf("%u %u\n", a, b);
}
return 0;
}

--
Ben.

Feb 23 '06 #6
On Thu, 23 Feb 2006 16:36:39 +0000, Ben Bacarisse wrote:
I think the following is more beginner-friendly:

#include <stdio.h>
#include <stdlib.h>


second include is, of course, not needed. I was panning to "exit" and
decided to "return" instead!

--
Ben.

Feb 23 '06 #7
On 2006-02-23, Ben Bacarisse <be********@bsb .me.uk> wrote:
On Thu, 23 Feb 2006 08:48:59 +0000, Richard G. Riley wrote:
Have a look at this code and work from there:

#include <stdio.h>
main()
{

unsigned long a,b;

FILE * pRead = fopen("test.dat ", "r");

if (pRead==NULL)
printf("File cannot be opened\n");

else
printf("Content s of test.dat : \n");

while ( !feof(pRead) ){
fscanf(pRead,"% u %u\n", &a,&b);
printf("%u %u\n",a,b);
}

}
This is a dodgy pattern to recommend. You get, I think, undefined


Thanks. You're right : I missed the return or bracketing at null check -
but then I wasnt looking to write it for him just to indicate the type
problems he had.
behaviour if you test a NULL FILE * with feof (I get a core dump rather
than any flying demons -- YMMV). You definitely get UB if you test for
end-of-file before reading anything (because there may be no data to read)
and your input is very sensitive to the format used (not technically a
problem, of course, but a beginenr will be baffled by the change in
behaviour caused by switching to "%u %u" from "%u %u\n").

I think the following is more beginner-friendly:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
unsigned long a, b;
FILE *pRead = fopen("test.dat ", "r");

if (pRead == NULL)
printf("File cannot be opened\n");
else {
printf("Content s of test.dat : \n");

while (fscanf(pRead," %u %u", &a,&b) == 2)
printf("%u %u\n", a, b);
}
return 0;
}

--
Remove evomer to reply
Feb 23 '06 #8

Ben Bacarisse wrote:

<snip>
This is a dodgy pattern to recommend. You get, I think, undefined
behaviour if you test a NULL FILE * with feof (I get a core dump rather
True, as it probably internally dereferences NULL pointer.
than any flying demons -- YMMV). You definitely get UB if you test for
end-of-file before reading anything (because there may be no data to read)
This however I believe is not the case. The Standard says only this:

7.19.10.2p2
The feof function tests the end-of-file indicator for the stream
pointed to by stream.

7.19.10.2p3
The feof function returns nonzero if and only if the end-of-file
indicator is set for
stream.

I see no requirement for any data to exist in the file (think empty
files), or any data to be read beforehand (think empty files again).
and your input is very sensitive to the format used (not technically a
problem, of course, but a beginenr will be baffled by the change in
behaviour caused by switching to "%u %u" from "%u %u\n").

I think the following is more beginner-friendly:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
unsigned long a, b;
FILE *pRead = fopen("test.dat ", "r");

if (pRead == NULL)
printf("File cannot be opened\n");
else {
printf("Content s of test.dat : \n");
Here, you make the same mistake as both OP and Richard. Even if the
`fopen` fails you'll try to read from the file.

while (fscanf(pRead," %u %u", &a,&b) == 2)
printf("%u %u\n", a, b);
}
return 0;
}


I believe my earlier post gave better advice.

--
BR, Vladimir

Feb 23 '06 #9
"Ben Bacarisse" <be********@bsb .me.uk> wrote in message
news:pa******** *************** *****@bsb.me.uk ...
I think the following is more beginner-friendly:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
unsigned long a, b;
FILE *pRead = fopen("test.dat ", "r");

if (pRead == NULL)
printf("File cannot be opened\n");
else {
printf("Content s of test.dat : \n");

while (fscanf(pRead," %u %u", &a,&b) == 2)
printf("%u %u\n", a, b);
You should consider closing the file here: fclose(pRead); }
return 0;
}

Feb 23 '06 #10

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

Similar topics

6
5651
by: Foxy Kav | last post by:
Hi, another question from me again, i was just wondering if anyone could give me a quick example of reading data from a file then placing the data into an array for some manipulation then reading that array back into another file. I've tried, but i can only read the data and place it on the screen, i cant get it into an array. Any help would be helpful.
2
3070
by: Jeevan | last post by:
Hi, I have an array of data (which I am getting from a socket connection). I am working on a program which acts on this data but the program is written to work on data from a file (not from an array). I cannot change anything in the program but can add some features by which I can convert this array of data into a file. The easiest thing would be to write the data into a file (in hard disk) and use it. But I will be working on thousands...
3
9512
by: Nick | last post by:
I have found a class that compresses and uncompresses data but need some help with how to use part of it below is the deflate method which compresses the string that I pass in, this works OK. At the end of this message is the inflate method this is where I get stuck I know that I need a byte array but because I am decompressing a string I have no idea of how big the byte array will need to be in the end (the inflate and deflate methods...
7
6063
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should populate a series of structures of specified variable composition. I have the structures created OK, but actually reading the files is giving me an error. Can I ask a simple question to start with: I'm trying to read the file using the...
10
2808
by: nuke1872 | last post by:
Hello guys, I have a file names network.txt which contains a matrix. I want to read this matrix as store it as an array. I am new to stuff like these...can anybody help me out !! Thanks nuke
6
5273
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
7
11790
by: ianenis.tiryaki | last post by:
well i got this assignment which i dont even have a clue what i am supposed to do. it is about reading me data from the file and load them into a parallel array here is the question: Step (1) Your first task is to write a program which reads this file into two parallel arrays in memory. One array contains the titles, and the other array contains the authors. The arrays are 'parallel' in the sense that the n-th element of the authors...
21
3064
by: Stephen.Schoenberger | last post by:
Hello, My C is a bit rusty (.NET programmer normally but need to do this in C) and I need to read in a text file that is setup as a table. The general form of the file is 00000000 USNIST00Z 00000000_00 0 000 000 000 0000 000 I need to read the file line by line and eventually parse out each piece of the file and store in arrays that correspond to the specific
3
2800
by: jordanbondo | last post by:
I have no clue why this isn't working. The top part that reads into size, shortTime, longTime, and threshold work fine. Down below where I try to do the exact same thing and read into x, i get segmentation fault every single time. It seems to me that everything is exactly the same. Reading a value from the file into an int*. Does anyone see what is wrong here? Don't worry about the array and other stuff. I'm going to be putting the values...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10216
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
10049
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...
1
9997
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.