473,748 Members | 10,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about read data from a text file.

Hello, all.

This is the text file named test.txt.

1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

I wanna to read the data to an array, as the follows:

#include <stdio.h>
#define MAX 30
int main()
{
int i = 0 ;
FILE *fp ;
int a[30] = {0};
if( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");
for(i = 0 ; i < MAX ; i++)
{
fscanf(fp, "%i", &a[i]) ;
printf("%i\t",a[i]);
}
fclose(fp);
return 0;
}

It is successful.

And I change the type of the array to float
....
float a[30];
....
fscanf(fp,"%f", &a[i]);
printf("%f\t",a[i]);
....

It works as well.

But when I change the type of the array to double
....
double a[30];
....
fscanf(fp,"%g", &a[i]);
printf(fp,"%g", a[i]);
....

It cannot work. It seams that the array is zero.

I wanna to know the reason and how can read the data to a double array.This is one question.

Another is that:
If the data file test.txt is in the following format,
a b c d e f g h i j
=============== =============== ===============
1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

how to read the file directly to the 3rd line? I mean that I just wanna to read the numbers.

I know fseek function can move the file pointer to a certain position.
But for a text file, how to caculate he offset?
If it can work, please give me your example for the above file.
I am learning the language at the beginning. Any encouragement will be helpful.
Apr 4 '07 #1
7 3057
"bowlderste r" <bo*********@gm ail.comha scritto nel messaggio
news:87******** ****@gmail.com. ..
[snip]
if( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");
If I redirect the output to a file, I won't be able to read the error until
I read that file.
You must write to stderr, not stdin. If you use perror() it will also add a
colon, a space, an explaination of the error, and a newline char.
perror("Open file fail");
Also, if the test fails, the rest of the program will run as if fp wasn't
NULL.
use exit(EXIT_FAILU RE); (you must #include <stdlib.hfor these).
for(i = 0 ; i < MAX ; i++)
{
fscanf(fp, "%i", &a[i]) ;
printf("%i\t",a[i]);
}
fclose(fp);
return 0;
}

It is successful.

And I change the type of the array to float
...
float a[30];
...
fscanf(fp,"%f", &a[i]);
printf("%f\t",a[i]);
...

It works as well.

But when I change the type of the array to double
...
double a[30];
...
fscanf(fp,"%g", &a[i]);
printf(fp,"%g", a[i]);
...

It cannot work. It seams that the array is zero.

I wanna to know the reason and how can read the data to a double
array.This is one question.

Another is that:
If the data file test.txt is in the following format,
a b c d e f g h i j
=============== =============== ===============
1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

how to read the file directly to the 3rd line? I mean that I just wanna to
read the numbers.

I know fseek function can move the file pointer to a certain position.
But for a text file, how to caculate he offset?
If it can work, please give me your example for the above file.
I am learning the language at the beginning. Any encouragement will be
helpful.


Apr 4 '07 #2
"bowlderste r" <bo*********@gm ail.comha scritto nel messaggio
news:87******** ****@gmail.com. ..
[snip]
>int a[30] = {0};
You meant a[MAX]. If you change MAX at the beginning and forget to change 30
here, that could be a problem.
if( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");
If I redirect the output to a file, I won't be able to read the error until
I read that file.
You must write to stderr, not stdin. If you use perror() it will also add a
colon, a space, an explaination of the error, and a newline char.
perror("Open file fail");
Also, if the test fails, the rest of the program will run as if fp wasn't
NULL.
use exit(EXIT_FAILU RE); (you must #include <stdlib.hfor these), or even
just return EXIT_FAILURE as you are in main()
But when I change the type of the array to double
...
double a[30];
...
fscanf(fp,"%g", &a[i]);
printf(fp,"%g", a[i]);
...

It cannot work. It seams that the array is zero.
http://c-faq.com/stdio/scanf2.html

Apr 4 '07 #3
In article <87************ @gmail.com>,
bowlderster <bo*********@gm ail.comwrote:
>If the data file test.txt is in the following format,
a b c d e f g h i j
============== =============== =============== =
1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895
>how to read the file directly to the 3rd line? I mean that I just wanna to read the numbers.
>I know fseek function can move the file pointer to a certain position.
But for a text file, how to caculate he offset?
You cannot do that. As the local man page says for fseek()

The ANSI C Standard restricts the use of offsets, when stream refers to a
text file. When operating on these files, the value of offset must be
zero unless whence is SEEK_SET. This restriction is necessary as the
unit of offsets may not be bytes on some systems, and arithmetic may not
meaningfully be performed on them.

And if you are using SEEK_SET on a text stream, then the value
you pass in must be the result of an ftell(), and ftell() on
a text stream theoretically returns an opaque value, not an
integral offset value.

Text files are not necessarily linearly structured (e.g., on the
VMS operating system), and even on systems that do structure text
files linearly, there is no way to query what the line termination
sequence is. (You can also run into issues such as the possibility
that the OS might consider as a valid line termination one or more
carriage returns before a linefeed; the first line might happen to
end CR LF internally, but the second line might happen to end
CR CR CR CR LF internally, so you cannot assign any fixed
predictable size for line termination offset calculations.)
If you were willing to lose portability and only deal with
systems that did use linear text files, and on which you knew
that the line termination was always the same size, then you
could read the file as a binary file and calculate byte offsets
if you knew the exact length of the first and second lines ahead
of time. But there is no portable way to fseek() to any given
line in a text stream -- not that doesn't involve reading
the file through once to find all the line offsets.
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
Apr 4 '07 #4
On Apr 4, 3:20 pm, bowlderster <bowlders...@gm ail.comwrote:
This is the text file named test.txt.

1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

I wanna to read the data to an array, as the follows:

#include <stdio.h>
#define MAX 30
int main()
{
int i = 0 ;
FILE *fp ;
int a[30] = {0};
if( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");
for(i = 0 ; i < MAX ; i++)
{
fscanf(fp, "%i", &a[i]) ;
printf("%i\t",a[i]);}

fclose(fp);
return 0;

}

But when I change the type of the array to double
...
double a[30];
...
fscanf(fp,"%g", &a[i]);
printf(fp,"%g", a[i]);
...

It cannot work. It seams that the array is zero.
fscanf(fp, "%lf", &a[i]) ;
Another is that:
If the data file test.txt is in the following format,
a b c d e f g h i j
=============== =============== ===============
1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

how to read the file directly to the 3rd line? I mean that I just wanna to read the numbers.
You could use fgets (twice) to read each of the first two lines.

Michael

Apr 4 '07 #5
"Army1987" <pl********@for .itwrites:
"bowlderste r" <bo*********@gm ail.comha scritto nel messaggio
news:87******** ****@gmail.com. ..
[snip]
>>int a[30] = {0};
You meant a[MAX]. If you change MAX at the beginning and forget to change 30
here, that could be a problem.
Thanks.I just want to test.
>
>if( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");
If I redirect the output to a file, I won't be able to read the error until
I read that file.
You must write to stderr, not stdin. If you use perror() it will also add a
colon, a space, an explaination of the error, and a newline char.
perror("Open file fail");
Also, if the test fails, the rest of the program will run as if fp wasn't
NULL.
use exit(EXIT_FAILU RE); (you must #include <stdlib.hfor these), or even
just return EXIT_FAILURE as you are in main()
>But when I change the type of the array to double
...
double a[30];
...
fscanf(fp,"%g" ,&a[i]);
printf(fp,"%g" ,a[i]);
...

It cannot work. It seams that the array is zero.
http://c-faq.com/stdio/scanf2.html
This is helpful.

Thank you.
Apr 4 '07 #6
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <87************ @gmail.com>,
bowlderster <bo*********@gm ail.comwrote:
>>If the data file test.txt is in the following format,
a b c d e f g h i j
============= =============== =============== ==
1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895
>>how to read the file directly to the 3rd line? I mean that I just wanna to read the numbers.
>>I know fseek function can move the file pointer to a certain position.
But for a text file, how to caculate he offset?

You cannot do that. As the local man page says for fseek()

The ANSI C Standard restricts the use of offsets, when stream refers to a
text file. When operating on these files, the value of offset must be
zero unless whence is SEEK_SET. This restriction is necessary as the
unit of offsets may not be bytes on some systems, and arithmetic may not
meaningfully be performed on them.

And if you are using SEEK_SET on a text stream, then the value
you pass in must be the result of an ftell(), and ftell() on
a text stream theoretically returns an opaque value, not an
integral offset value.

Text files are not necessarily linearly structured (e.g., on the
VMS operating system), and even on systems that do structure text
files linearly, there is no way to query what the line termination
sequence is. (You can also run into issues such as the possibility
that the OS might consider as a valid line termination one or more
carriage returns before a linefeed; the first line might happen to
end CR LF internally, but the second line might happen to end
CR CR CR CR LF internally, so you cannot assign any fixed
predictable size for line termination offset calculations.)
If you were willing to lose portability and only deal with
systems that did use linear text files, and on which you knew
that the line termination was always the same size, then you
could read the file as a binary file and calculate byte offsets
if you knew the exact length of the first and second lines ahead
of time. But there is no portable way to fseek() to any given
line in a text stream -- not that doesn't involve reading
the file through once to find all the line offsets.
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
I know a lot from your words.

Apr 5 '07 #7
bowlderster wrote:
This is the text file named test.txt.

1041 1467 7334 9500 2169 7724 3478 3358 9962 7464
6705 2145 6281 8827 1961 1491 3995 3942 5827 6436
6391 6604 4902 1153 1292 4382 9421 1716 2718 2895

I wanna to read the data to an array, as the follows:
"want to" standard english is easier to read.

code is more readable if indented and with appropriate whitespace
#include <stdio.h>
#define MAX 30

int main()
int main (void)
is better style
{
int i = 0 ;
FILE *fp ;
int a[30] = {0};

if ( (fp = fopen("test.txt ", "r")) == NULL )
printf("Open file fail!!!\n");

for (i = 0 ; i < MAX ; i++)
{
fscanf(fp, "%i", &a[i]) ;
always check the return value of fscanf()

printf("%i\t",a[i]);
}

fclose(fp);
return 0;
}
<snip>
I am learning the language at the beginning. Any encouragement will be helpful.
not bad for a beginner
--
Nick Keighley

Apr 5 '07 #8

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

Similar topics

8
11477
by: LG | last post by:
Just have a question with regards to the clipboard, and how to read what other applications (Adobe InDesignCS) place in the clipboard. I am currently in the process of creating a booklet from a database, and I need the data to be laid out in a tabular format, and set out in a specific way. At the current point in time, I am copy/pasting the raw text from the database into a table layout in InDesign. What I was thinking is that if I could...
7
2021
by: dan | last post by:
hey peeps, i am completely new at c++ and i need some help with an assignment. it is basically about file i/o with fstreams. i understand how to open a file with fstream, but how would you read, write and display data that is contained in... for example a regular text file? another question... how would you be able to count the number of words in the text and then c it out (cout)? how would you replace specific words in the text file?...
1
2212
by: siliconwafer | last post by:
Hi All, here is one code: int main() { FILE*fp; unsigned long a; fp = fopen("my_file.txt","w+"); a = 24; fprintf(fp,"%ld",a); while(fscanf(fp,"%ld",&a) == 1) {
5
1734
by: Darrel | last post by:
I thought this warranted a new thread. Yesterday I asked about access relatively static content...is it better to read from the DB, or just grab a text file. It was suggested that I use the DB and look into the Application Cache settings. I found a good article here: http://www.developer.com/net/net/article.php/1477771
9
2415
by: CGW | last post by:
I asked the question yesterday, but know better how to ask it, today: I'm trying to use the File.Copy method to copy a file from a client to server (.Net web app under IIS ). It looks to me that when I give a path like @"C:\holdfiles\myfile.txt" it looks on the server C drive. How do I pull from the client? Do I need a different class and/or method? Filestream? -- Thanks,
10
2148
by: Avi | last post by:
Hi I need to read in a large set of text files (9GB+ each) into a database table based on fixed width lengths. There are several ways to complete this, but I am wondering if anyone has insight into the FASTEST way to read in the data and chop it up ahead of posting it into the DB. So far, things work, but they are far slower than expected.
1
2566
by: sharpy | last post by:
i hope this is a simple answered question this program has been annoying me for some time, its pretty much the first thing i have attempted to do in perl. its a pretty simple guestbook type thing. it all works ok in that it saves all the newest information to a log file. however in falls down in the whole putting-the-old-data-back part. which is really quite a desirable function in my script. at the moment i have only four fields. the script...
6
3099
by: kath | last post by:
Hi all, Platform: winxp Version: Python 2.3 I have a task of reading files in a folder and creating an one excel file with sheets, one sheet per file, with sheet named as filename. I am facing problem in handling special characters. I am using XLRD and XLW package to read/write from/to file. But facing problem in handling special characters. I am getting encode error.
0
851
by: Smoke | last post by:
Im developing a custom app that has to read a file generated from other program, actually, the file is pretty much a mail message, which contains the subject, to, from, body, etc etc and also the attaches and its binary data. My problem is that i cannot seems to understand how can i read the "binary" data from the file at the specific possition, or even worst how to know where to start read. As an example, the files contains something...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
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
9537
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...
1
6795
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
6073
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
4599
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
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
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
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.