473,239 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,239 software developers and data experts.

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 1792
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...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.