473,397 Members | 1,974 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,397 software developers and data experts.

request for code review

Hi,

I have a file with a single column containing observations of an
experiment, the number of observations is not known in advance and I
have to read them all into an array, I am using realloc to keep on
changing the size of the array. My program is below. I would be
grateful for any comments.

Deb
/************************************************** ****************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BFSIZ 1024

/*fname is the name of the file,on return nr contains the number of
observations, the function returns a pointer to the array containing
the observations if sucessful and NULL otherwise*/

double
*read_dbl_array(char *fname,int *nr)
{
size_t nd=32,/* space for doubles is allocated in multiples of nd
*/
nread=0,/*number of lines read so far*/
ninc=0;
FILE *fp;
double *d=NULL;
char buf[BFSIZ];
*nr=0;
fp=fopen(fname,"r");
if(NULL==fp)
{
perror(NULL);
return NULL;
}
while(fgets(buf,sizeof(buf),fp))
{
int i;
if(0==(nread%nd))/* time to allocate more memory*/
{
double *t;
t=realloc(d,(++ninc)*sizeof(*t)*nd);
if(NULL==t)
{
fclose(fp);
free(d);
return NULL;
}
d=t;
}
i=sscanf(buf,"%lf",d+(nread++));
if(i != 1)
{
fprintf(stderr,"invalid input at line %lu\n",(unsigned
long) nread);
fclose(fp);
free(d);
return NULL;
}
}
if(ferror(fp))
{
perror("error reading file");
fclose(fp);
free(d);
return NULL;
}
fclose(fp);
*nr=nread;
return d;
}

int
main(void)
{
char fname[FILENAME_MAX+1],*s;
double *d=NULL;
int nr=0;
printf("give file name\n");
fgets(fname,sizeof(fname),stdin);
if((s=strchr(fname,'\n')))
*s=0;
d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\nFirst value:%f\tLast
value:%f",nr,d[0],d[nr-1]);
}
free(d);
return 0;
}
Nov 13 '05 #1
3 1264
I've a doubt, doesn't calling realloc for every entry slow down your
code, here's what I did when I didn't know num. of entries in file in
advance.
Count num. of lines in file by calling the "system" command "wc -l
filename > numlines.txt"

numlines.txt contains the num. of lines in the file. Read this number.

You now call calloc only once.

system spawns a shell and executes the cmd. (sort of system specific)
Debashish Chakravarty wrote:
Hi,

I have a file with a single column containing observations of an
experiment, the number of observations is not known in advance and I
have to read them all into an array, I am using realloc to keep on
changing the size of the array. My program is below. I would be
grateful for any comments.

Deb
/************************************************** ****************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BFSIZ 1024

/*fname is the name of the file,on return nr contains the number of
observations, the function returns a pointer to the array containing
the observations if sucessful and NULL otherwise*/

double
*read_dbl_array(char *fname,int *nr)
{
size_t nd=32,/* space for doubles is allocated in multiples of nd
*/
nread=0,/*number of lines read so far*/
ninc=0;
FILE *fp;
double *d=NULL;
char buf[BFSIZ];
*nr=0;
fp=fopen(fname,"r");
if(NULL==fp)
{
perror(NULL);
return NULL;
}
while(fgets(buf,sizeof(buf),fp))
{
int i;
if(0==(nread%nd))/* time to allocate more memory*/
{
double *t;
t=realloc(d,(++ninc)*sizeof(*t)*nd);
if(NULL==t)
{
fclose(fp);
free(d);
return NULL;
}
d=t;
}
i=sscanf(buf,"%lf",d+(nread++));
if(i != 1)
{
fprintf(stderr,"invalid input at line %lu\n",(unsigned
long) nread);
fclose(fp);
free(d);
return NULL;
}
}
if(ferror(fp))
{
perror("error reading file");
fclose(fp);
free(d);
return NULL;
}
fclose(fp);
*nr=nread;
return d;
}

int
main(void)
{
char fname[FILENAME_MAX+1],*s;
double *d=NULL;
int nr=0;
printf("give file name\n");
fgets(fname,sizeof(fname),stdin);
if((s=strchr(fname,'\n')))
*s=0;
d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\nFirst value:%f\tLast
value:%f",nr,d[0],d[nr-1]);
}
free(d);
return 0;
}


Nov 13 '05 #2

"Debashish Chakravarty" <de********@yahoo.com> schrieb im Newsbeitrag
news:ad**************************@posting.google.c om...
Hi,

I have a file with a single column containing observations of an
experiment, the number of observations is not known in advance and I
have to read them all into an array, I am using realloc to keep on
changing the size of the array. My program is below. I would be
grateful for any comments.

Deb
/************************************************** *************************
***/ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BFSIZ 1024

/*fname is the name of the file,on return nr contains the number of
observations, the function returns a pointer to the array containing
the observations if sucessful and NULL otherwise*/

double
*read_dbl_array(char *fname,int *nr)
{
size_t nd=32,/* space for doubles is allocated in multiples of nd
*/
nread=0,/*number of lines read so far*/
ninc=0;
Just personal preference - I'd write every definition in an extra line:
size_t nd = 32;
size_t nread = 0;
size_t ninc = 0;
FILE *fp;
double *d=NULL;
char buf[BFSIZ];
*nr=0;
fp=fopen(fname,"r");
if(NULL==fp)
I like that way of using == :)
Anyway, here i'd just write
if(!fp)
{
perror(NULL);
return NULL;
}
while(fgets(buf,sizeof(buf),fp))
No need for parens around buf
{
int i;
if(0==(nread%nd))/* time to allocate more memory*/
{
double *t;
t=realloc(d,(++ninc)*sizeof(*t)*nd);
No need for parens around *t
if(NULL==t)
{
fclose(fp);
free(d);
return NULL;
}
d=t;
}
i=sscanf(buf,"%lf",d+(nread++));
if(i != 1)
{
fprintf(stderr,"invalid input at line %lu\n",(unsigned
long) nread);
fclose(fp);
free(d);
return NULL;
}
}
if(ferror(fp))
{
perror("error reading file");
fclose(fp);
free(d);
return NULL;
}
fclose(fp);
*nr=nread;
return d;
}

int
main(void)
{
char fname[FILENAME_MAX+1],*s;
I am not sure about that, but as I understand the definition of FILENAME_MAX
in 7.19.1 of n869 FILENAME_MAX should be big enough to hold the longest
possible filename plus the terminating '\0'. It says:
(emphasis mine)

...which expands to an integer constant expression that is the size needed
for an array of
char large enough to hold the LONGEST FILENAME STRING that the
implementation
guarantees can be opened;
However, the +1 does not hurt..

And again I prefer an extra line for each variable. You are not using much
whitespace, and it took me a second glance to see, that the above line
defined two variables.
double *d=NULL;
int nr=0;
printf("give file name\n");
fgets(fname,sizeof(fname),stdin);
if((s=strchr(fname,'\n')))
*s=0;
If there is no newline found in the input it is quite likely, that the user
entered an invalid filename. Maybe it would be better to extend the if block
so, that it covers the whole processing and prompt the user for a correct
filename if no '\n' is present.
(untested, typos etc likely)

int
main(void)
{
char fname[FILENAME_MAX+1];
char *s;
double *d=NULL;
int nr=0;
int retry_count = 0;

printf("give file name\n");
do
{
fgets(fname,sizeof(fname),stdin);
s=strchr(fname,'\n');
if(s)
{
*s=0;
d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\n"
"First value:%f\t"
"Last value:%f",
nr,d[0],d[nr-1]);
free(d);
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
else
{
puts("Probably incorrect filename. "
"Please try again");
do
{
fgets(fname,sizeof(fname),stdin);
}while(!strchr(fname,'\n'));
}
}while(retry_count++ < 5 && !s);
puts("RTFM!!");
return EXIT_FAILURE;
}

d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\nFirst value:%f\tLast
value:%f",nr,d[0],d[nr-1]);
}
free(d);
return 0;
}


I liked your code :)
Robert
Nov 13 '05 #3

"Debashish Chakravarty" <de********@yahoo.com> schrieb im Newsbeitrag
news:ad**************************@posting.google.c om...
Hi,

I have a file with a single column containing observations of an
experiment, the number of observations is not known in advance and I
have to read them all into an array, I am using realloc to keep on
changing the size of the array. My program is below. I would be
grateful for any comments.

Deb
/************************************************** *************************
***/ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BFSIZ 1024

/*fname is the name of the file,on return nr contains the number of
observations, the function returns a pointer to the array containing
the observations if sucessful and NULL otherwise*/

double
*read_dbl_array(char *fname,int *nr)
{
size_t nd=32,/* space for doubles is allocated in multiples of nd
*/
nread=0,/*number of lines read so far*/
ninc=0;
Just personal preference - I'd write every definition in an extra line:
size_t nd = 32;
size_t nread = 0;
size_t ninc = 0;
FILE *fp;
double *d=NULL;
char buf[BFSIZ];
*nr=0;
fp=fopen(fname,"r");
if(NULL==fp)
I like that way of using == :)
Anyway, here i'd just write
if(!fp)
{
perror(NULL);
return NULL;
}
while(fgets(buf,sizeof(buf),fp))
No need for parens around buf
{
int i;
if(0==(nread%nd))/* time to allocate more memory*/
{
double *t;
t=realloc(d,(++ninc)*sizeof(*t)*nd);
No need for parens around *t
if(NULL==t)
{
fclose(fp);
free(d);
return NULL;
}
d=t;
}
i=sscanf(buf,"%lf",d+(nread++));
if(i != 1)
{
fprintf(stderr,"invalid input at line %lu\n",(unsigned
long) nread);
fclose(fp);
free(d);
return NULL;
}
}
if(ferror(fp))
{
perror("error reading file");
fclose(fp);
free(d);
return NULL;
}
fclose(fp);
*nr=nread;
return d;
}

int
main(void)
{
char fname[FILENAME_MAX+1],*s;
I am not sure about that, but as I understand the definition of FILENAME_MAX
in 7.19.1 of n869 FILENAME_MAX should be big enough to hold the longest
possible filename plus the terminating '\0'. It says:
(emphasis mine)

...which expands to an integer constant expression that is the size needed
for an array of
char large enough to hold the LONGEST FILENAME STRING that the
implementation
guarantees can be opened;
However, the +1 does not hurt..

And again I prefer an extra line for each variable. You are not using much
whitespace, and it took me a second glance to see, that the above line
defined two variables.
double *d=NULL;
int nr=0;
printf("give file name\n");
fgets(fname,sizeof(fname),stdin);
if((s=strchr(fname,'\n')))
*s=0;
If there is no newline found in the input it is quite likely, that the user
entered an invalid filename. Maybe it would be better to extend the if block
so, that it covers the whole processing and prompt the user for a correct
filename if no '\n' is present.
(untested, typos etc likely)

int
main(void)
{
char fname[FILENAME_MAX+1];
char *s;
double *d=NULL;
int nr=0;
int retry_count = 0;

printf("give file name\n");
do
{
fgets(fname,sizeof(fname),stdin);
s=strchr(fname,'\n');
if(s)
{
*s=0;
d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\n"
"First value:%f\t"
"Last value:%f",
nr,d[0],d[nr-1]);
free(d);
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
else
{
puts("Probably incorrect filename. "
"Please try again");
do
{
fgets(fname,sizeof(fname),stdin);
}while(!strchr(fname,'\n'));
}
}while(retry_count++ < 5 && !s);
puts("RTFM!!");
return EXIT_FAILURE;
}

d=read_dbl_array(fname,&nr);
if(d)
{
printf("%d lines read\nFirst value:%f\tLast
value:%f",nr,d[0],d[nr-1]);
}
free(d);
return 0;
}


I liked your code :)
Robert

Nov 13 '05 #4

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

Similar topics

18
by: Ben Hanson | last post by:
I have created an open source Notepad program for Windows in C++ that allows search and replace using regular expressions (and a few other extras). It is located at...
9
by: Adam Monsen | last post by:
I kindly request a code review. If this is not an appropriate place for my request, where might be? Specific questions are in the QUESTIONS section of the code. ...
6
by: Daniel Rimmelzwaan | last post by:
I want to send a biztalk document to an aspx page, and I need to see some sample code, because I just can't make it work. I have a port with transport type HTTP, pointing to my aspx page, something...
2
by: William F. Robertson, Jr. | last post by:
Some of my users are receiving an error: Server Error in '/' Application. ---------------------------------------------------------------------------- ---- Request timed out. Description: An...
0
by: Jack Wright | last post by:
Dear All, I have a web Application "http://localhost/Web/WebForm1.aspx" that calls a WebService from "http://localhost/webserviceapp/service1.asmx"...I have set the executionTimeout to 10 secs in...
2
by: Terry Mulvany | last post by:
namespace CIBWeb { public class BasePage : System.Web.UI.Page { public BasePage() { } protected override void OnInit(EventArgs e) {
7
by: Shapiro | last post by:
I have a scenario where I log a resquest to a database table and update the request with a corresponding response including the response time. I am using an HttpModule to do this. My challenge...
3
by: nms | last post by:
I've an ASP.net web site, Since last some days, Users are experiencing problem when they try to generate reports (for a large date range) it says, Request timed out. Description: An unhandled...
2
by: patrice.pare | last post by:
Hello, Here is a summary of my Dev Environment: I use Visual Studio 2005 Team Suite SP1 with Crystal Report XI SP1 on a Windows XP SP2 development workstation. I also use SQL Server 2000 SP4. ...
3
by: vijaykumardahiya | last post by:
Dear Sir, I have two queries. First question is: I have a Html page. On which Have two buttons Submit and Issue. I want when I click on Sumit button request should be go to submit.jsp. and When I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...
0
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...

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.