473,473 Members | 1,614 Online
Bytes | Software Development & Data Engineering Community
Create 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 1795
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"),puts("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"),puts("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.dat","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"),puts("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.dat","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("Bad 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(double) * ++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"),puts("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.dat","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("Bad 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"),puts("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.dat","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("Bad 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.dat","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_Keith) 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 misunderstanding 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.net
Apr 3 '06 #9

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

Similar topics

4
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
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...
4
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 =...
0
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....
7
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...
1
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...
6
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...
2
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?...
1
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
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...
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
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,...
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
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,...
0
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...
0
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,...
1
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...
0
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...
0
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 ...

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.