473,785 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

c file reading

can someone direct me to some compilable example code which reads in
floating points or integers from a tab delimited file (either to
variables or arrays) please? this is driving me mad today

thanks

stew

Mar 17 '06 #1
8 1812
st************* @hotmail.co.uk wrote:
can someone direct me to some compilable example code which reads in
floating points or integers from a tab delimited file (either to
variables or arrays) please? this is driving me mad today


What do you have so far?

Here is what I came up with, it reads values into a double and then
prints out the values:

#include <stdio.h>

int main (void) {
double d;
int i;
/* Look for a number, store in d, quit on EOF */
while ((i = scanf("%lf", &d)) != EOF)
if (i == 1) /* Successful conversion */
printf("Read %f\n", d);
else
scanf("%*s"),pu ts("Bad input"); /* Get rid of next word and try
again */
return 0;
}

If you are stuck with the storing into an array part or trying to be
able to ready both floats and integers and differentiate between the
two this won't help much. Show us what you have and be more specific
about what you are trying to accomplish and we can be of more
assistance.

Robert Gamble

Mar 17 '06 #2

Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
can someone direct me to some compilable example code which reads in
floating points or integers from a tab delimited file (either to
variables or arrays) please? this is driving me mad today


What do you have so far?

Here is what I came up with, it reads values into a double and then
prints out the values:

#include <stdio.h>

int main (void) {
double d;
int i;
/* Look for a number, store in d, quit on EOF */
while ((i = scanf("%lf", &d)) != EOF)
if (i == 1) /* Successful conversion */
printf("Read %f\n", d);
else
scanf("%*s"),pu ts("Bad input"); /* Get rid of next word and try
again */
return 0;
}

If you are stuck with the storing into an array part or trying to be
able to ready both floats and integers and differentiate between the
two this won't help much. Show us what you have and be more specific
about what you are trying to accomplish and we can be of more
assistance.

Robert Gamble


thanks Robert

it is really the file opeing and referencing in the scanf. your code
looks ok, but I need the file open and just get confused with the
arguments in
FILE *stream, *fopen();

and

stream = fopen("myfile.d at","r");

stew

Mar 17 '06 #3

st************* @hotmail.co.uk wrote:
Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
can someone direct me to some compilable example code which reads in
floating points or integers from a tab delimited file (either to
variables or arrays) please? this is driving me mad today


What do you have so far?

Here is what I came up with, it reads values into a double and then
prints out the values:

#include <stdio.h>

int main (void) {
double d;
int i;
/* Look for a number, store in d, quit on EOF */
while ((i = scanf("%lf", &d)) != EOF)
if (i == 1) /* Successful conversion */
printf("Read %f\n", d);
else
scanf("%*s"),pu ts("Bad input"); /* Get rid of next word and try
again */
return 0;
}

If you are stuck with the storing into an array part or trying to be
able to ready both floats and integers and differentiate between the
two this won't help much. Show us what you have and be more specific
about what you are trying to accomplish and we can be of more
assistance.

Robert Gamble


thanks Robert

it is really the file opeing and referencing in the scanf. your code
looks ok, but I need the file open and just get confused with the
arguments in
FILE *stream, *fopen();

and

stream = fopen("myfile.d at","r");


Here is a version that will open the files provided on the commandline
one at a time and process them:

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

int main (int argc, char *argv[]) {
double d;
int i, j;
FILE *fp;

if (argc < 2) {
fprintf(stderr, "No filename provided\n");
return EXIT_FAILURE;
}

for (j = 1; j < argc; j++) {
errno = 0;
fp = fopen(argv[j], "r");
if (!fp) {
fprintf(stderr, "Could not open %s: %s\n", argv[j], errno ?
strerror(errno) : "Unknown reason");
continue;
}
while ((i = fscanf(fp, "%lf", &d)) != EOF)
if (i == 1)
printf("Read %f\n", d);
else
fscanf(fp, "%*s"),puts("Ba d input");
}
return 0;
}

It's pretty straight-forward but if you have any questions feel free to
ask. As far as getting confused about function prototypes, etc., did
your implementation come with any documentation? If not then it might
serve you well to pick up a good reference on C programming, I
recommend "C: A Reference Manual" by Harbison and Steele.

Robert Gamble

Mar 17 '06 #4
st************* @hotmail.co.uk wrote:
can someone direct me to some compilable example code which reads in
floating points or integers from a tab delimited file (either to
variables or arrays) please? this is driving me mad today


Here's a /knock-up/ ... no doubt someone will soon be along to say why it's
either crap, or could be done in a one liner etc.
The input file was [the spaces were tab characters of course!]:

0.123 3.143 6.4 0 333.44 232.454 34334.4 232 10

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

int main(void)
{
FILE * in = NULL;

if((in = fopen("c:\\test .txt", "rb")) != NULL)
{
long tabCount = 0;
long allCount = 0;
long l = 0;

char c;

char * p = NULL; // For strtok().
char * buffer = NULL; // Holds the inout file.
double * dbs = NULL; // Array of doubles - from the file.

// Read file - store size, and number of tabs seen.
//
while((c = fgetc(in)) != EOF)
{
if(c == '\t')
{
tabCount++;
}

allCount++;
}

rewind(in);

// Alloc space for tab-seperated double values.
//
dbs = malloc(sizeof(d ouble) * ++tabCount);

// Alloc space for the whole file.
//
buffer = calloc(allCount + 1, 1);

// Fill and terminate the buffer from the file.
//
fread(buffer, 1, allCount, in);
//
buffer[allCount] = '\0';

fclose(in);

// Parse for tabs.
//
p = strtok(buffer, "\t");

while(p)
{
// Convert each toekn returned by strtok().
//
dbs[l++] = atof(p);

p = strtok(NULL, "\t");
}

// Done.

// Dump doubles array for checking.
//
while(l)
{
printf("%lf\n", dbs[--l]);
}

free(buffer);
free(dbs);
}

return 0;
}
--
==============
*Not a pedant*
==============
Mar 17 '06 #5

Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
> can someone direct me to some compilable example code which reads in
> floating points or integers from a tab delimited file (either to
> variables or arrays) please? this is driving me mad today

What do you have so far?

Here is what I came up with, it reads values into a double and then
prints out the values:

#include <stdio.h>

int main (void) {
double d;
int i;
/* Look for a number, store in d, quit on EOF */
while ((i = scanf("%lf", &d)) != EOF)
if (i == 1) /* Successful conversion */
printf("Read %f\n", d);
else
scanf("%*s"),pu ts("Bad input"); /* Get rid of next word and try
again */
return 0;
}

If you are stuck with the storing into an array part or trying to be
able to ready both floats and integers and differentiate between the
two this won't help much. Show us what you have and be more specific
about what you are trying to accomplish and we can be of more
assistance.

Robert Gamble


thanks Robert

it is really the file opeing and referencing in the scanf. your code
looks ok, but I need the file open and just get confused with the
arguments in
FILE *stream, *fopen();

and

stream = fopen("myfile.d at","r");


Here is a version that will open the files provided on the commandline
one at a time and process them:

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

int main (int argc, char *argv[]) {
double d;
int i, j;
FILE *fp;

if (argc < 2) {
fprintf(stderr, "No filename provided\n");
return EXIT_FAILURE;
}

for (j = 1; j < argc; j++) {
errno = 0;
fp = fopen(argv[j], "r");
if (!fp) {
fprintf(stderr, "Could not open %s: %s\n", argv[j], errno ?
strerror(errno) : "Unknown reason");
continue;
}
while ((i = fscanf(fp, "%lf", &d)) != EOF)
if (i == 1)
printf("Read %f\n", d);
else
fscanf(fp, "%*s"),puts("Ba d input");
}
return 0;
}

It's pretty straight-forward but if you have any questions feel free to
ask. As far as getting confused about function prototypes, etc., did
your implementation come with any documentation? If not then it might
serve you well to pick up a good reference on C programming, I
recommend "C: A Reference Manual" by Harbison and Steele.


thanks very much for your help. i should spend some time starting
again on C from the beginning (it has been 5 years or so). i tend to
rush things a bit without doing the groundwork in the hope i will learn
as i go along. and i usually program by cut and pasting when it comes
to fortran, c and java without necessarily having a deeper
understanding. anyway, that compiles and runs ok, and i may just take
you up on your advice for the book (I had K&R many years ago).

have a nice weekend

stew

Mar 17 '06 #6
Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
Robert Gamble wrote:
st************* @hotmail.co.uk wrote:
> can someone direct me to some compilable example code which reads in
> floating points or integers from a tab delimited file (either to
> variables or arrays) please? this is driving me mad today

What do you have so far?

Here is what I came up with, it reads values into a double and then
prints out the values:

#include <stdio.h>

int main (void) {
double d;
int i;
/* Look for a number, store in d, quit on EOF */
while ((i = scanf("%lf", &d)) != EOF)
if (i == 1) /* Successful conversion */
printf("Read %f\n", d);
else
scanf("%*s"),pu ts("Bad input"); /* Get rid of next word and try
again */
return 0;
}

If you are stuck with the storing into an array part or trying to be
able to ready both floats and integers and differentiate between the
two this won't help much. Show us what you have and be more specific
about what you are trying to accomplish and we can be of more
assistance.

Robert Gamble


thanks Robert

it is really the file opeing and referencing in the scanf. your code
looks ok, but I need the file open and just get confused with the
arguments in
FILE *stream, *fopen();

and

stream = fopen("myfile.d at","r");


Here is a version that will open the files provided on the commandline
one at a time and process them:

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

int main (int argc, char *argv[]) {
double d;
int i, j;
FILE *fp;

if (argc < 2) {
fprintf(stderr, "No filename provided\n");
return EXIT_FAILURE;
}

for (j = 1; j < argc; j++) {
errno = 0;
fp = fopen(argv[j], "r");
if (!fp) {
fprintf(stderr, "Could not open %s: %s\n", argv[j], errno ?
strerror(errno) : "Unknown reason");
continue;
}
while ((i = fscanf(fp, "%lf", &d)) != EOF)
if (i == 1)
printf("Read %f\n", d);
else
fscanf(fp, "%*s"),puts("Ba d input");


Forgot to close the file here:

fclose(fp);

Robert Gamble

Mar 17 '06 #7
st************* @hotmail.co.uk writes:
[...]
it is really the file opeing and referencing in the scanf. your code
looks ok, but I need the file open and just get confused with the
arguments in
FILE *stream, *fopen();

and

stream = fopen("myfile.d at","r");


I'm not quite sure what you mean here, but if the line
FILE *stream, *fopen();
is part of your code, it shouldn't be. You don't need to declare
fopen yourself; just do a "#include <stdio.h>" and use the prototype
from the header (which is guaranteed to ce correct).

--
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.
Mar 17 '06 #8
On 17 Mar 2006 08:37:17 -0800, st************* @hotmail.co.uk wrote:
<snip>
thanks very much for your help. i should spend some time starting
again on C from the beginning (it has been 5 years or so). i tend to
rush things a bit without doing the groundwork in the hope i will learn
as i go along. and i usually program by cut and pasting when it comes
to fortran, c and java without necessarily having a deeper
understanding. anyway, that compiles and runs ok, and i may just take
you up on your advice for the book (I had K&R many years ago).

Let me encourage you not to do that. More than most other languages,
probably all the ones you are likely to come across nowadays, C can
punish you for copying or otherwise writing code you don't understand.

In most other programming languages commonly available, most of the
mistakes you are likely to make by accident or misunderstandin g will
either be caught outright or will only (!) produce a wrong output.
(Except assembler, the only exception is the 'old' part of Fortran,
which you mention, but the 'newer' parts do offer this safety. Well,
and the roughly C part of C++, but I assumed that was obvious.)

C is often likened metaphorically to a sharp knife, even a surgeon's
scalpel -- you can do impressive and even wonderful things with that
if you know how to use it, but can easily injure yourself or others if
you don't. With the types of computers you are likely to be using this
injury will be only metaphorical -- destroyed or corrupted data, or
lost/wasted time -- but still unpleasant; and in hobby or toy
programming solely for yourself it will probably be you and not
others; but these are still worth avoiding.
- David.Thompson1 at worldnet.att.ne t
Apr 3 '06 #9

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

Similar topics

4
3069
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
19
10380
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much text is available until I have read it... which seems to imply that multiple reads of the input stream will be inevitable. Now I can correctly find the number of characters available by: |
4
9843
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile = tmpfile(); /* write into tmpFile */ ...
0
3941
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header, example, and DLL:...
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...
1
64196
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
6
248998
Atran
by: Atran | last post by:
Hello: In this article: You will learn to Write or Read A Text File. Let's Begin: First Create a new project (ConsoleApp or WinApp). And Make sure your program uses these namespaces: using System; using System.IO; using System.Diagnostics;
2
3703
by: Zach | last post by:
I compiled a game client and it crashed (segmentation fault) resulting in a core file being generated. I'm trying to find out exactly what caused it to crash. Any ideas how I can do this with gdb? In the Makefile can I just add a "-g" flag to have the binary produced with debugging symbols? The source is written in ANSI C. This is what I have now: "CC = gcc" The client binary is 433680 and the core file produced when it crashed
1
2673
by: dwaterpolo | last post by:
Hi Everyone, I am trying to read two text files swY40p10t3ctw45.col.txt and solution.txt and compare them, the first text file has a bunch of values listed like: y y y y y y y
13
10454
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.
0
9484
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
9957
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...
0
8983
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...
1
7505
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
5386
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
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
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
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.