473,473 Members | 1,918 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to read data ?

Hay Guys can you all suggest me the points on the below issue

Problem :

The thing is that I have the data some thing like this.

1486, 2168, 3751, 9074, 12134, 13944, 17983, 19173, 21190, 21820,
1730, 2640, 3450, 4870, 6126, 7876, 15644, 17817, 20294, 21902,
2070, 3025, 4333, 5854, 7805, 9231, 10597,
16047........................... soo onnnnnn

now this data I have stored into the ABC.txt file.

Now what I have to do is, that I have to read these data from the file
in sequence from left to right.

And store into the Buffer.

So please let me know how to achive this.
Thank in advance
Ranjeet
Nov 14 '05 #1
19 2474
ra***********@gmail.com (ranjeet) wrote in
news:77**************************@posting.google.c om:
Problem :

The thing is that I have the data some thing like this.

1486, 2168, 3751, 9074, 12134, 13944, 17983, 19173, 21190, 21820,
1730, 2640, 3450, 4870, 6126, 7876, 15644, 17817, 20294, 21902,
2070, 3025, 4333, 5854, 7805, 9231, 10597,
16047........................... soo onnnnnn

now this data I have stored into the ABC.txt file.

Now what I have to do is, that I have to read these data from the file
in sequence from left to right.

And store into the Buffer.

So please let me know how to achive this.


This should be possible with fopen() and fread(). You may want to use
malloc() for your buffer too.

--
- Mark ->
--
Nov 14 '05 #2
"Mark A. Odell" <od*******@hotmail.com> wrote:
ra***********@gmail.com (ranjeet) wrote in
news:77**************************@posting.google.c om:
1486, 2168, 3751, 9074, 12134, 13944, 17983, 19173, 21190, 21820,
1730, 2640, 3450, 4870, 6126, 7876, 15644, 17817, 20294, 21902,
2070, 3025, 4333, 5854, 7805, 9231, 10597,
16047........................... soo onnnnnn

now this data I have stored into the ABC.txt file.

Now what I have to do is, that I have to read these data from the file
in sequence from left to right.


This should be possible with fopen() and fread().


It's text in a text file. I'd use fgets() followed by sscanf(), or quite
possibly (if I didn't want to report file format errors with line
numbers) fscanf().

Richard
Nov 14 '05 #3
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote in message news:<41****************@news.individual.net>...
"Mark A. Odell" <od*******@hotmail.com> wrote:
ra***********@gmail.com (ranjeet) wrote in
news:77**************************@posting.google.c om:
1486, 2168, 3751, 9074, 12134, 13944, 17983, 19173, 21190, 21820,
1730, 2640, 3450, 4870, 6126, 7876, 15644, 17817, 20294, 21902,
2070, 3025, 4333, 5854, 7805, 9231, 10597,
16047........................... soo onnnnnn

now this data I have stored into the ABC.txt file.

Now what I have to do is, that I have to read these data from the file
in sequence from left to right.
This should be possible with fopen() and fread().


It's text in a text file. I'd use fgets() followed by sscanf(), or quite
possibly (if I didn't want to report file format errors with line
numbers) fscanf().


I have written a simple program check this. I am also using that there
will be a FULL STOP at the end of the text file.

SEE the COMMENTs in the program. below !!!

#include<stdlib.h>
#include<stdio.h>
int main() {

FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)

int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;

if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {

printf("\nerror\n");
exit(0);
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %d\n",arr[index]);

return 0;

}

Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.

what simply i am doing is that i m using this concept. Below
see the below code
#include<stdlib.h>
#include<stdio.h>
int main() {

FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)

int *arr, nofcomma = 0, index = 0, intindex = 0;
double *arry_float;

char fch;

if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {

printf("\nerror\n");
exit(0);
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
arry_float = (double *)malloc(nofcomma + 2);

rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow (2,13));
++intindex;
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %lf \n", arry_float[index]);
return 0;

}
Now I having the problem and geting the segmentation fault
please let me know what is the fault i am doing ??????


Richard

Nov 14 '05 #4
ra***********@gmail.com (ranjeet) wrote:
I have written a simple program check this. I am also using that there
will be a FULL STOP at the end of the text file.
You shouldn't rely on this too much. The program as you've written it
will be very confused, and could easily cause undefined behaviour, on
malformed input. A less trusting program is safer.
#include<stdlib.h>
#include<stdio.h>
int main() {

FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)
Are you absolutely sure of this? What do you think happens when someone
forgets a comma - or even intentionally leaves one out to break your
program?
int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;

if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {

printf("\nerror\n");
exit(0);
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers
No, you're counting the number of commas. You're _hoping_ that this is
also the number of integers.
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
The cast is completely superfluous. Ditch it.
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
What are these magic numbers? Do you perhaps mean '0' and '9'? Or maybe
even isdigit()?
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {
What happens if someone puts 123.45 as a number in the file? What,
indeed, happens when you encounter "12abc89"?
buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
And here, what happens if someone enters 98765 as one of the numbers?
Are you sure your ints are 32 bit? What do you think atoi() does when it
tries to read a number which overflows? It's much safer to use strtol().
Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.

what simply i am doing is that i m using this concept. Below
see the below code
Most of that code is identical to the code above, so insert the same
comments, but also...
double *arry_float;
This name is misleading. double is a floating point type, but it's not
the same thing as float.
else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf); ^^^^^^^^^^
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow (2,13));
++intindex;

^^^^^^^^^^^
Twice.

Richard
Nov 14 '05 #5
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote in message news:<41****************@news.individual.net>...
ra***********@gmail.com (ranjeet) wrote:
I have written a simple program check this. I am also using that there
will be a FULL STOP at the end of the text file.
You shouldn't rely on this too much. The program as you've written it
will be very confused, and could easily cause undefined behaviour, on
malformed input. A less trusting program is safer.
#include<stdlib.h>
#include<stdio.h>
int main() {

FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)


Are you absolutely sure of this? What do you think happens when someone
forgets a comma - or even intentionally leaves one out to break your
program?


This is correct what You said. But for my case the All the numbers are
integers and less then (<32768), I accept the test cases u have suggested.
int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;

if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {

printf("\nerror\n");
exit(0);
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers
No, you're counting the number of commas. You're _hoping_ that this is
also the number of integers.
Yes I am counting the numbers of commas And in this way i will get the

number of Integers wihc will be equal to the Number of commas + 1
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.


The cast is completely superfluous. Ditch it.

I Know according to C89 standars we should Not cast the malloc.
but the thing is that, in many programming books malloc has been casted.
can you tell me the specific reason why to not cast malloc ??
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
What are these magic numbers? Do you perhaps mean '0' and '9'? Or maybe
even isdigit()?


Yes i am checking the number between 0 tp 9.
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {
What happens if someone puts 123.45 as a number in the file? What,
indeed, happens when you encounter "12abc89"?


for this I have not wrtitten the error code so please beg you pardon.
buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
And here, what happens if someone enters 98765 as one of the numbers?
Are you sure your ints are 32 bit? What do you think atoi() does when it
tries to read a number which overflows? It's much safer to use strtol().


can u tell me About the strtol() ?? some basic so can I proceed.
Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.

what simply i am doing is that i m using this concept. Below
see the below code
Most of that code is identical to the code above, so insert the same
comments, but also...
double *arry_float;


This name is misleading. double is a floating point type, but it's not
the same thing as float.


I think this has mislead you any way its a array which is of double type.
nothing more then this. rather I should have written double array_store;
else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf); ^^^^^^^^^^
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow (2,13));
++intindex;

^^^^^^^^^^^

Twice.
sorry its single... please skip the last line ( lsat increment)

Now my simple question is that You are reading the integers from
the Text file. Now you are allocating the dynamic memory for it.
and storing the intergers form the text file.

If i want to allocate the dynamic memeory for the double array_float;
then how to proceed.

The thing what I have to do is :

step 1 Read each integer from the text file
step 2 Store the integer in the array
step 3 again read the same integer from the array,
step 4 do the manipulation on it.
step 5 store it into the diffrent array

the array in which i am goin to store is of double type.

please guide me on the step 3 to step 5



Richard

Nov 14 '05 #6
On 18 Nov 2004 20:10:26 -0800, in comp.lang.c , ra***********@gmail.com
(ranjeet) wrote:
Yes I am counting the numbers of commas And in this way i will get the number of Integers wihc will be equal to the Number of commas + 1


only if the number of commas is correct.....
> arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.


The cast is completely superfluous. Ditch it.

I Know according to C89 standars we should Not cast the malloc.
but the thing is that, in many programming books malloc has been casted.


No decent /C/ programming book will cast malloc. C++ ones will, because you
require the cast in C++ but then thats a different language.
can you tell me the specific reason why to not cast malloc ??
read
http://benpfaff.org/writings/clc/malloc-cast.html
and
http://benpfaff.org/writings/clc/malloc-sizeof.html.
will help you. Thanks to Ben for making his comments so easily available.
can u tell me About the strtol() ?? some basic so can I proceed.
It will be in your helpfile/manual/manpages.
step 1 Read each integer from the text file
step 2 Store the integer in the array
step 3 again read the same integer from the array,
step 4 do the manipulation on it.
step 5 store it into the diffrent array

the array in which i am goin to store is of double type.

please guide me on the step 3 to step 5


you know how many integers you read, so malloc an array of doubles large
enough, loop over the first array copying the data from the int array to
the double array.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #7
Mark McIntyre wrote:
No decent /C/ programming book will cast malloc.


Er um..., and if they do, they post an errata page.

http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

42(§6.5, toward the end): The remark about casting the return
value of malloc ("the proper method is to declare
.... then explicitly coerce") needs to be rewritten.
The example is correct and works, but the advice is debatable in
the context of the 1988-1989 ANSI/ISO standards. It's not necessary
(given that coercion of void * to ALMOSTANYTYPE * is automatic),
and possibly harmful if malloc, or a proxy for it,
fails to be declared as returning void *. The explicit cast
can cover up an unintended error. On the other hand, pre-ANSI,
the cast was necessary, and it is in C++ also.

--
pete
Nov 14 '05 #8
On Fri, 19 Nov 2004 12:45:38 GMT, in comp.lang.c , pete
<pf*****@mindspring.com> wrote:
Mark McIntyre wrote:
No decent /C/ programming book will cast malloc.


Er um..., and if they do, they post an errata page.


I should have said "any decent C programming book that was actually
published since ISO C became established"... :-)
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #9
Mark McIntyre <ma**********@spamcop.net> wrote...
pete <pf*****@mindspring.com> wrote:
Mark McIntyre wrote:
No decent /C/ programming book will cast malloc.


Er um..., and if they do, they post an errata page.
[http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html]


I should have said "any decent C programming book that was actually
published since ISO C became established"... :-)


Even if ANSI C was finalised at the time of writing, they would quite
probably still have used a C++ compiler to test the code samples.

--
Peter
Nov 14 '05 #10
Mark McIntyre <ma**********@spamcop.net> wrote in message news:<nd********************************@4ax.com>. ..
On Fri, 19 Nov 2004 12:45:38 GMT, in comp.lang.c , pete
<pf*****@mindspring.com> wrote:
Mark McIntyre wrote:
No decent /C/ programming book will cast malloc.


Er um..., and if they do, they post an errata page.


I should have said "any decent C programming book that was actually
published since ISO C became established"... :-)


Thank you Guys for all your guidence. I was able to proceed my work
Nov 14 '05 #11
On 19 Nov 2004 20:57:37 -0800, in comp.lang.c , ai***@acay.com.au (Peter
Nilsson) wrote:
Mark McIntyre <ma**********@spamcop.net> wrote...
pete <pf*****@mindspring.com> wrote:
> Mark McIntyre wrote:
> > No decent /C/ programming book will cast malloc.
>
> Er um..., and if they do, they post an errata page.
> [http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html]


I should have said "any decent C programming book that was actually
published since ISO C became established"... :-)


Even if ANSI C was finalised at the time of writing, they would quite
probably still have used a C++ compiler to test the code samples.


If you do a google groups search, you'll find a comment on this idea from
Bjarne Stroustrup. You might also want to read the errata listing for the
book, which is K&Rs comment on their mistake.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #12
In <63*************************@posting.google.com> ai***@acay.com.au (Peter Nilsson) writes:
Mark McIntyre <ma**********@spamcop.net> wrote...
pete <pf*****@mindspring.com> wrote:
> Mark McIntyre wrote:
> > No decent /C/ programming book will cast malloc.
>
> Er um..., and if they do, they post an errata page.
> [http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html]


I should have said "any decent C programming book that was actually
published since ISO C became established"... :-)


Even if ANSI C was finalised at the time of writing, they would quite
probably still have used a C++ compiler to test the code samples.


This is properly documented in the Preface, but it doesn't justify the
advice to cast malloc calls that the errata actually addresses.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #13
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
#include<stdlib.h>
#include<stdio.h>
int main() {
you should probably take the file name from argv[]
FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)
Make that larger !

int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;
fch must be declared int to accomodate for fgetc() returning all char values and
EOF
if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {
"r" is enough, get rid of this directory stuff

printf("\nerror\n");
fprintf(stderr, ...) for error diagnostics
exit(0);
don't exit with 0 status on error.
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers
indent your code with spaces
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
The pedants have focussed on the stupid unnecessary cast. But much worse is the
fact that you do not allocate enough space for your array of int, this is the
cause of your segmentation fault ! use this instead:
arr = calloc(nofcomma + 1, sizeof(*arr));
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))
buf[index++] = fch ;
you should check that index stays within bounds of the buf array:
if (index < sizeof(buf) - 2) {
buf[index++] = fch;
} else {
// complain about invalid number in input file instead of crashing
}

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
no check for overflow here either. You may look up strtol() to achieve this,
but it is a bit tricky.
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %d\n",arr[index]);

return 0;

}

Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.
not fine yet I'm afraid, but getting there.

[...] arr = (int *) malloc(nofcomma + 2); file://allocate so much of memory.
arry_float = (double *)malloc(nofcomma + 2);
obviously same problem as above, use this instead
arry_float = malloc(nofcomma + 1, sizeof(*arry_float);

And it is misleading to call an array of double arry_float.

rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
don't increment intindex yet, you need it to index the other array and will
increment it after.
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow (2,13));

quite inefficient : use this instead:
arry_float[intindex] = arr[intindex] / 8192.0;

I wouldn't be surprised if you meant pow(2,15) = 32768.0 instead ;-)
++intindex;
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %lf \n", arry_float[index]);
not an integer, the format string should be changed too ;-)
be aware that %lf is the same as %f for printf(), but not for scanf()


return 0;

}
Now I having the problem and geting the segmentation fault
please let me know what is the fault i am doing ??????


Correct your program along my remarks, and that should be fixed.

--
Chqrlie.

Nov 14 '05 #14

In article <co**********@reader1.imaginet.fr>, "Charlie Gordon" <ne**@chqrlie.org> writes:
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
char fch;


fch must be declared int to accomodate for fgetc() returning all char values
and EOF
if (fch > 47 && fch < 58)


don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))


I think that should be

if (isdigit((unsigned char)fch))

Calling any of the is* functions with an argument that isn't EOF or
within the range of unsigned char causes UB. Unless I'm mistaken,
in an implementation where plain char is signed, fgetc can return a
negative int value: if the next character is a value which would be
negative when represented by char, then its representation when
promoted or converted to int is still negative.

(And, of course, ranjeet would need to include <ctype.h>.)

--
Michael Wojcik mi************@microfocus.com

The guy who's fast in the mountain pass is the coolest.
-- _Initial D: Second Stage_
Nov 14 '05 #15
mw*****@newsguy.com (Michael Wojcik) wrote:
In article <co**********@reader1.imaginet.fr>, "Charlie Gordon" <ne**@chqrlie.org> writes:
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
char fch;


fch must be declared int to accomodate for fgetc() returning all char values
and EOF
if (fch > 47 && fch < 58)


don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))


I think that should be

if (isdigit((unsigned char)fch))

Calling any of the is* functions with an argument that isn't EOF or
within the range of unsigned char causes UB. Unless I'm mistaken,
in an implementation where plain char is signed, fgetc can return a
negative int value:


You are mistaken. fgetc() returns an int for this very reason.

[7.19.7.1#2]
# If the end-of-file indicator for the input stream pointed to by stream
# is not set and a next character is present, the fgetc function obtains
# that character as an unsigned char converted to an int and advances
# the associated file position indicator for the stream (if defined).

Richard
Nov 14 '05 #16
"Michael Wojcik" <mw*****@newsguy.com> wrote in message
news:co*********@news4.newsguy.com...

In article <co**********@reader1.imaginet.fr>, "Charlie Gordon" <ne**@chqrlie.org> writes:
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
char fch;


fch must be declared int to accomodate for fgetc() returning all char values
and EOF
I should have written : all unsigned char values and EOF ;-)
if (fch > 47 && fch < 58)


don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))


I think that should be

if (isdigit((unsigned char)fch))


Not in this particular case.
Calling any of the is* functions with an argument that isn't EOF or
within the range of unsigned char causes UB. Unless I'm mistaken,
in an implementation where plain char is signed, fgetc can return a
negative int value: if the next character is a value which would be
negative when represented by char, then its representation when
promoted or converted to int is still negative.
You are mistaken : fgetc() and getc(), getchar(), fgetchar() all return exactly
that : EOF or the value of an unsigned char.
This way EOF can be defined to -1 without clashing with the value of '\377'
(assuming chars signed by default and 8 bit bytes).
This makes it very clear that the char type should be unsigned by default. The
standard library is inconsistent with the char being signed by default. getc()
== '\377' is always false with signed chars.
The reason chars may be signed by default is an historical inconsistency between
the language and the original stdio library, that was not fixed when the
'signed' keyword was introduced, and was not deprecated by ANSI because they
were too lame to break existing code, but paved the way for more subtle bugs,
plaguing the language with one more implementation choice and countless bugs and
internationalization issues.
Most modern compilers I've seen default to signed chars.
Personally I use the appropriate flag to make 'char' unsigned by default. Not
all compilers have that flexibility.
gcc does, and the glibc makes its best efforts to allow the is*() family of
macros from ctype.h work correctly for values between CHAR_MIN and UCHAR_MAX,
that is with both signed chars and unsigned chars and EOF.

(And, of course, ranjeet would need to include <ctype.h>.)


Of course.

--
Chqrlie

Nov 14 '05 #17
"Charlie Gordon" <ne**@chqrlie.org> wrote in message news:<co**********@reader1.imaginet.fr>...
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
#include<stdlib.h>
#include<stdio.h>
int main() {


you should probably take the file name from argv[]
FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)


Make that larger !

int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;


fch must be declared int to accomodate for fgetc() returning all char values and
EOF
if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {


"r" is enough, get rid of this directory stuff

printf("\nerror\n");


fprintf(stderr, ...) for error diagnostics
exit(0);


don't exit with 0 status on error.
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers


indent your code with spaces
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.


The pedants have focussed on the stupid unnecessary cast. But much worse is the
fact that you do not allocate enough space for your array of int, this is the
cause of your segmentation fault ! use this instead:
arr = calloc(nofcomma + 1, sizeof(*arr));
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)


don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))
buf[index++] = fch ;


you should check that index stays within bounds of the buf array:
if (index < sizeof(buf) - 2) {
buf[index++] = fch;
} else {
// complain about invalid number in input file instead of crashing
}

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);


no check for overflow here either. You may look up strtol() to achieve this,
but it is a bit tricky.
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %d\n",arr[index]);

return 0;

}

Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.


not fine yet I'm afraid, but getting there.

[...]
arr = (int *) malloc(nofcomma + 2); file://allocate so much of memory.
arry_float = (double *)malloc(nofcomma + 2);


obviously same problem as above, use this instead
arry_float = malloc(nofcomma + 1, sizeof(*arry_float);

And it is misleading to call an array of double arry_float.

rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);


don't increment intindex yet, you need it to index the other array and will
increment it after.
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow

(2,13));

quite inefficient : use this instead:
arry_float[intindex] = arr[intindex] / 8192.0;

I wouldn't be surprised if you meant pow(2,15) = 32768.0 instead ;-)
++intindex;
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %lf \n", arry_float[index]);


not an integer, the format string should be changed too ;-)
be aware that %lf is the same as %f for printf(), but not for scanf()


return 0;

}
Now I having the problem and geting the segmentation fault
please let me know what is the fault i am doing ??????


Correct your program along my remarks, and that should be fixed.


It was really a nice comment/remark to my code.
I tried to grasp the each line what you suggetsed
the thing what i annalysed that you have given me some tips of
optimistaion also. You reviwed my code in great intelectual fashion

thanks a lot.

Ranjeet
Nov 14 '05 #18
"Charlie Gordon" <ne**@chqrlie.org> wrote in message news:<co**********@reader1.imaginet.fr>...
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
#include<stdlib.h>
#include<stdio.h>
int main() {
you should probably take the file name from argv[]
FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)


Make that larger !

int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;


fch must be declared int to accomodate for fgetc() returning all char values and
EOF
if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {


"r" is enough, get rid of this directory stuff

printf("\nerror\n");


fprintf(stderr, ...) for error diagnostics
exit(0);


don't exit with 0 status on error.
}

while ((fch = fgetc(fp))!= EOF) {

if (fch == ',')
nofcomma++; // count the no of integers


indent your code with spaces
}

arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.


The pedants have focussed on the stupid unnecessary cast. But much worse is the
fact that you do not allocate enough space for your array of int, this is the
cause of your segmentation fault ! use this instead:
arr = calloc(nofcomma + 1, sizeof(*arr));
rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)


don't rely on ASCII, make it both more portable and more readable :
if (fch >= '0' && fch <= '9')
or
if (isdigit(fch))
buf[index++] = fch ;


you should check that index stays within bounds of the buf array:
if (index < sizeof(buf) - 2) {
buf[index++] = fch;
} else {
// complain about invalid number in input file instead of crashing
}

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);


no check for overflow here either. You may look up strtol() to achieve this,
but it is a bit tricky.


how to use this strtol(). can i have a simple code which has
implemented this strtol() funtion in it. Please
provide me with the sample code.

Thanks In Advance
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %d\n",arr[index]);

return 0;

}

Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.


not fine yet I'm afraid, but getting there.

[...]
arr = (int *) malloc(nofcomma + 2); file://allocate so much of memory.
arry_float = (double *)malloc(nofcomma + 2);


obviously same problem as above, use this instead
arry_float = malloc(nofcomma + 1, sizeof(*arry_float);

And it is misleading to call an array of double arry_float.

rewind(fp); // set the pointer aagain to the beginning

while ((fch = fgetc(fp))!= EOF) {

if (fch > 47 && fch < 58)
buf[index++] = fch ;

else if (fch == ',' || fch == '.') {

buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);


don't increment intindex yet, you need it to index the other array and will
increment it after.
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow

(2,13));

quite inefficient : use this instead:
arry_float[intindex] = arr[intindex] / 8192.0;

I wouldn't be surprised if you meant pow(2,15) = 32768.0 instead ;-)
++intindex;
}

}

for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %lf \n", arry_float[index]);


not an integer, the format string should be changed too ;-)
be aware that %lf is the same as %f for printf(), but not for scanf()


return 0;

}
Now I having the problem and geting the segmentation fault
please let me know what is the fault i am doing ??????


Correct your program along my remarks, and that should be fixed.

Nov 14 '05 #19
"ranjeet" <ra***********@gmail.com> wrote in message
news:77**************************@posting.google.c om...
"Charlie Gordon" <ne**@chqrlie.org> wrote in message

news:<co**********@reader1.imaginet.fr>...
"ranjeet" <ra***********@gmail.com> wrote in message
news:77*************************@posting.google.co m...
buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);


no check for overflow here either. You may look up strtol() to achieve this, but it is a bit tricky.


how to use this strtol(). can i have a simple code which has
implemented this strtol() funtion in it. Please
provide me with the sample code.


In your example you may replace atoi(buf) with :

long val;
val = strtol(buf, NULL, 10);
if (val > 32767L || val < -32768L) {
/* handle the error */
...
} else {
arr[intindex++] = val;
}

You can use appropriate values for the minimum and maximum values you want to
check against.
If you want to allow val to reach the limits of the long type, checking for
overflow then becomes a little trickier as you will have to set errno to 0 prior
to calling strtol() and check that it is still 0 after the call.

--
Chqrlie.

PS: avoid quoting too much from the message you reply to. Only the relevant
parts are needed for the discussion.

Nov 14 '05 #20

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

Similar topics

1
by: Peter Ammon | last post by:
I would like to read from a pipe in which data may arrive slowly. From experimenting, it looks like os.read() will block until it returns the maximum amount of data you asked for, in the second...
2
by: Gunnar | last post by:
Hello, I've just written a CPP program that reads integers from a binary file, and used this code while (my_ifstram.read( (char* ) &number, sizeof(int)) { // do something with number } My...
4
by: francis70 | last post by:
Hi, I have these 2 problem? Is there a way in Oracle to read UNCOMMITED data. i.e. in Oracle the normal behaviour is that a user's updates to a table are visible to other users ONLY when the...
11
by: Markus Breuer | last post by:
I have a question about oracle commit and transactions. Following scenario: Process A performs a single sql-INSERT into a table and commits the transaction. Then he informs process B (ipc) to...
18
by: jas | last post by:
Hi, I would like to start a new process and be able to read/write from/to it. I have tried things like... import subprocess as sp p = sp.Popen("cmd.exe", stdout=sp.PIPE)...
0
by: Peter | last post by:
I am having a problem reading an Excel file that is XML based. The directory I am reading contains Excel files that can be of two types. Either generic Microsoft based or XML based. I am reading...
0
by: phplasma | last post by:
Hey, I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express. I have successfully made...
6
by: arnuld | last post by:
This works fine, I welcome any views/advices/coding-practices :) /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a program to store each line from a file into a *...
4
by: zl2k | last post by:
hi, there I have a appendable binary file of complex data structure named data.bin created by myself. It is written in the following format: number of Data, Data array Suppose I have...
1
by: Sachin Garg | last post by:
I have a program which opens a fstream in binary input+output mode, creating the file if it doesn't exists. But writing doesn't works after reading, it must be something obvious that I am not aware...
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: 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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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 ...
0
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...

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.