By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,853 Members | 2,144 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,853 IT Pros & Developers. It's quick & easy.

Replacing fgets

P: n/a
Hello C World & Fanatics

I am trying replace fgets and provide a equavivalant function of
BufferedInputReader::readLine.
I am calling this readLine function as get_Stream.
In the line 4 where default_buffer_length is changed from 4 --24 code
works fine.
But on the same line if I change the value of default_buffer_length
from 4 --10 and I get a memory error.
And if the change the value of the same variable from 4 --1024 bytes;
the code just fails. It does not display an content on the file/ stdout
stream.

I am trying return the pointer of chars from the line from the object
variable ' temp ' into the pointer of chars variable ' result '; and I
do not know how to do this in the line 50 or 51.

And a last question
If I try to return copy the object variable ' temp ' memory address to
the ' result ' memory address I will have to call the function free in
the line 80 or so.
I want to avoid calling function free in the line 80 or so; because
this way some other user can use this code.
Current Code:
short check_Bits(int decimal){
int mask=sizeof(char)*8; /* 8 bits */
short bit = 0;
for(mask,bit = 0;mask; bit = (( mask & decimal) ? 1:0),mask = mask >>
1);
return bit;
}

1 short get_Stream(FILE* pSource,char* result){
2 char* final_buffer;final_buffer=0;
3 int default_buffer_length;
4 default_buffer_length=4; /* nibble */
5 int buffer_length = default_buffer_length;
6 char *temp;temp = 0;
7 char byte = 0;
8 int temp_length= 0;
9 /*allocate 1024 bytes to buffer object*/
10 char * buffer;buffer = 0;buffer = (char
*)malloc(default_buffer_length); /*current fgets line */
11 temp = (char *)malloc(buffer_length+default_buffer_length); /*
temporary line + current buffer */
12 /* read the file contents */
13 do{
14 fgets(buffer,default_buffer_length+1,pSource);
15 temp_length = strlen(temp);
16 /* append text */
17 if(temp_length == buffer_length){
18 buffer_length = buffer_length+default_buffer_length;
19 final_buffer = (char *)malloc(buffer_length);
20 final_buffer = strcpy(final_buffer,temp);
21 free(temp);temp = 0;
22 temp = (char
*)malloc(buffer_length+default_buffer_length);
23 temp = strcpy(temp,final_buffer);
24 free(final_buffer);final_buffer = 0;
25 }
26
27 if(temp_length == 0)
28 temp = strcpy(temp,buffer);
29 else
30 temp = strcat(temp,buffer);
40 byte = buffer[default_buffer_length-(check_Bits(buffer_length) ==
0? 2:1)];
41 }while((byte != '\n' && byte != '\r') && byte!=0 && byte!=0xFF);
42 free(buffer);
43 /* free the contents */
44 buffer_length = buffer_length-(check_Bits(strlen(temp)) == 1? 2:1);
45 temp[buffer_length]='\0';
45 short ret=EXIT_SUCCESS;
47 if(byte==0xFF || byte==0 || byte==EOF)
48 ret = EXIT_FAILURE;
49 else {
50 ret = EXIT_SUCCESS;
51 printf("%s\nDone",temp);
52 }
53 /* free the contents */
54 free(temp);
55 return ret;
56 }
57 /*End of Function */
58
59 void main(int argc,const char* argv[]){
60
61 FILE* pSourceFile=0;
62 const char* ATOMIC_NAME;
63
64 ATOMIC_NAME = "/home/generic/algorith.txt";
65 /*ATOMIC_NAME = "/usr/share/magic";*/
66
67 printf("%s\n",ATOMIC_NAME);
68 pSourceFile = fopen(ATOMIC_NAME,"rb");
69
70 if(pSourceFile==NULL){
71 printf("File not found");
72 exit(EXIT_FAILURE);
73 }
74 else
75 fseek(pSourceFile,SEEK_SET,SEEK_SET);
76
77 char* ret = "";
78 if(feof(pSourceFile)==EXIT_SUCCESS)
79 if(get_Stream(pSourceFile,ret)==EXIT_SUCCESS)
80 printf("<2>\n%s<1>",ret);
81 fclose(pSourceFile);
82 }
Can somebody help.
I will use these same function on HP-UX platform later on so therefore
I cannot use a function getline which is already available in GCC but
not available on the HP-UX platform.

Thanks.

Sep 17 '06 #1
Share this Question
Share on Google+
32 Replies


P: n/a
FireHead wrote:
>
I am trying replace fgets and provide a equavivalant function of
BufferedInputReader::readLine.
This is a C++ operation.
>
.... snip ...
>
Can somebody help.
I will use these same function on HP-UX platform later on so
therefore I cannot use a function getline which is already
available in GCC but not available on the HP-UX platform.
Your code is illegible and not compilable (incomplete, poorly
formatted, etc.). In addition C++ is off-topic here, we deal
solely with ISO standard C.

I suggest you try ggets, which is written in pure standard C, and
is available at:

<http://cbfalconer.home.att.net/download/>

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski

--
Posted via a free Usenet account from http://www.teranews.com

Sep 17 '06 #2

P: n/a
Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
<http://cbfalconer.home.att.net/download/>
and I have found a few memory leaks.
I have download the entire code and find the memory leak.
Any I cannot use C++ (I wish) as this presenting C code will be
transitioned to UNIX.
But eventhough if I use C++ algorithmcally speaking I am still pointed
at same problem/issue.
> BufferedInputReader::readLine.
Based on ISO C99 standard BufferedInputRead is the namespace and
readLine which as usual is just a function.

If I am you presribing me to use your PDL (Public Domain Licence) code.

Thanks for reply thou.
CBFalconer wrote:
FireHead wrote:

I am trying replace fgets and provide a equavivalant function of
BufferedInputReader::readLine.

This is a C++ operation.
... snip ...

Can somebody help.
I will use these same function on HP-UX platform later on so
therefore I cannot use a function getline which is already
available in GCC but not available on the HP-UX platform.

Your code is illegible and not compilable (incomplete, poorly
formatted, etc.). In addition C++ is off-topic here, we deal
solely with ISO standard C.

I suggest you try ggets, which is written in pure standard C, and
is available at:

<http://cbfalconer.home.att.net/download/>

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski

--
Posted via a free Usenet account from http://www.teranews.com
Sep 17 '06 #3

P: n/a
FireHead said:
Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
> <http://cbfalconer.home.att.net/download/>
and I have found a few memory leaks.
<snorfle>

Well, Chuck, that's one in your eye. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 17 '06 #4

P: n/a
In article <11**********************@m73g2000cwd.googlegroups .com>,
FireHead <sa************@htech.health.nsw.gov.auwrote:
>> BufferedInputReader::readLine.
>Based on ISO C99 standard BufferedInputRead is the namespace and
readLine which as usual is just a function.
Can you point me to the part of the C99 standard where it describes
namespaces?

-- Richard
Sep 17 '06 #5

P: n/a
Richard Tobin said:
In article <11**********************@m73g2000cwd.googlegroups .com>,
FireHead <sa************@htech.health.nsw.gov.auwrote:
>>> BufferedInputReader::readLine.
>>Based on ISO C99 standard BufferedInputRead is the namespace and
readLine which as usual is just a function.

Can you point me to the part of the C99 standard where it describes
namespaces?
6.2.3 describes name spaces. The name spaces of C are:

1) label names;
2) tags;
3) struct/union members;
4) ordinary identifiers.

So yes, C has name spaces, but no, C doesn't have namespaces. The space in
the name makes all the difference.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 17 '06 #6

P: n/a
FireHead wrote:
>
I am looking at this code more of C code rather than a C++ code.
I have tried this code.
<http://cbfalconer.home.att.net/download/>
and I have found a few memory leaks.
ggets allocates a buffer, which must then be freed when the input
string is no longer needed. This is plainly marked in the source,
and done in the usage illustrations. The code outline should be
(assuming lines do not need to be preserved when the next line is
read):

char *line;

while (0 == ggets(&line) {
/* operate on the line */
free(line);
}

a non-zero return from ggets indicates either EOF, i/o error, or
lack of allocatable memory.

The included demo freverse.c illustrates the action when the line
is needed for a longer period.

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski

--
Posted via a free Usenet account from http://www.teranews.com

Sep 17 '06 #7

P: n/a
Richard Heathfield wrote:
FireHead said:
>Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
>> <http://cbfalconer.home.att.net/download/>
and I have found a few memory leaks.

<snorfle>

Well, Chuck, that's one in your eye. :-)
What can you do?

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski

--
Posted via a free Usenet account from http://www.teranews.com

Sep 17 '06 #8

P: n/a
CBFalconer said:
Richard Heathfield wrote:
>FireHead said:
>>Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
<http://cbfalconer.home.att.net/download/>
and I have found a few memory leaks.

<snorfle>

Well, Chuck, that's one in your eye. :-)

What can you do?
I know, I know. You, at least, and possibly some others here, will
understand the relevance of the following (true) story:

David Niven once hired some decorators for a medium-sized task in his home.
Wallpaper tables, paper rolls, paste everywhere, you get the picture.
Anyway, being an impeccable host, he provided the decorators with
sandwiches for lunch - caviare, naturally.

They grumbled. Quietly, even politely, but nevertheless they were definitely
grumbling. Mr Niven enquired as to the source of their discontent, and was
told in no uncertain terms: "the blackberry jam tastes of fish!"

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 17 '06 #9

P: n/a
"FireHead" <sa************@htech.health.nsw.gov.auwrites:
Hello CBFalconer
Please don't top-post. See <http://www.caliburn.nl/topposting.html>.

[snip]
Any I cannot use C++ (I wish) as this presenting C code will be
transitioned to UNIX.
<OT>There are C++ compilers for Unix.</OT>
But eventhough if I use C++ algorithmcally speaking I am still pointed
at same problem/issue.
If you have a question about algorithms, try comp.programming.

[...]
If I am you presribing me to use your PDL (Public Domain Licence) code.
I can't quite figure out what you mean by that, but "public domain" is
not a license.

--
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.
Sep 17 '06 #10

P: n/a

CBFalconer <cb********@yahoo.comwrote in message
news:45***************@yahoo.com...
FireHead wrote:

I am trying replace fgets and provide a equavivalant function of
BufferedInputReader::readLine.

This is a C++ operation.
How perceptive...
... snip ...

Can somebody help.
I will use these same function on HP-UX platform later on so
therefore I cannot use a function getline which is already
available in GCC but not available on the HP-UX platform.

Your code is illegible and not compilable (incomplete, poorly
formatted, etc.). In addition C++ is off-topic here, we deal
solely with ISO standard C.
Who said anything about C++, other than saying he wanted
equivalent functionality of a C++ function for reading lines out of
a buffer?
I suggest you try ggets, which is written in pure standard C, and
is available at:

<http://cbfalconer.home.att.net/download/>
OK, for the sake of discussion, replacing fgets() with some type
of equivalent function where you START with a unopened file really
doesn't get you much, EXCEPT when you want to do interactive editing
of the file contents (fgets() is fine for general parsing and searching),
and in that case you probably want something more than an equivalent
of the largely brain-dead fgets().

The real value of a fgets() equivalent is when you are dealing with
text buffers that didn't come from a file stream (or maybe testing
purposes), and you just want to do some simple parsing and searching.

With all that being said, sometimes I use something like this:

#define LINEMAX 512 /* UNIX line length */

#define FIRSTLINE 0
#define NEXTLINE MAXLONG
#define ENDOFTEXT MAXLONG

/* like fgets() except works on a text buffer rather than a file stream */
/* each call gets next line in buffer, returns buffer position */
/* last call for a buffer gets nothing, returns 0, function is reset */
unsigned long get_text_line
(char *text_buf,char *line_buf,unsigned long start) {
static unsigned long text_idx;
unsigned long line_start=text_idx;
unsigned line_idx=0;
char line_buf[LINEMAX];

if(start==FIRSTLINE) text_idx=0;

else if(start!=NEXTLINE) text_idx=start;

while(line_idx<LINEMAX) {
line_buf[line_idx]=text_buf[text_idx];
if(text_buf[text_idx]=='\0') {
break;
}
if(text_buf[text_idx]=='\n') {
line_buf[line_idx]='\0';
text_idx++,line_idx++;
break;
}
text_idx++,line_idx++;
}

if(line_idx==0) return ENDOFTEXT;
else return line_start;
}

Note that this is not really the "equivalent" of fgets(), but more
like the combination of fgets() with ftell() and fseek() and rewind(),
and even more brain-dead than even all of those put together.
Hard to say which is klunkier to use; note that the function returns
the START of the line in the buffer, as opposed to the typical
use of while(fgets()!=NULL) {/* did we find something? */ break;}
ftell(), where we now know the position of the line AFTER the
found search text. (Also note that I replace the '\n' terminating
newline character with the NUL '\0' character in the returned
string, cuz you rarely want the newline for searching and parsing.)

Now, to completely go from an opened text file to reading it from
a buffer, here's how I PORTABLY get the file into the buffer:

/* portable method to get a usable approx size of an open text file stream
*/
/* probably best to open file as "rt" */
unsigned long get_text_file_size(FILE *fl_strm) {
unsigned long file_size=0;

while(feof(fl_strm)==0) {
fgetc(fl_strm);
file_size++;
}

rewind(fl_strm);

return file_size;
}

/* reads a file into a text buffer */
unsigned read_file_to_buffer(FILE *fl_strm,char **ptr_buf_ptr) {
char *buf_ptr=NULL;
unsigned long char_idx=0;
unsigned long file_size=0;

if(!((file_size=get_text_file_size(fl_strm))>0))
return FALSE;

if((buf_ptr=malloc(file_size))==NULL) {
printf("\nNot enough memory to allocate file buffer");
return FALSE;
}
else *ptr_buf_ptr=buf_ptr;

while(feof(fl_strm)==0) {
buf_ptr[char_idx]=fgetc(fl_strm);
char_idx++;
}
buf_ptr[char_idx]='\0';

return TRUE;
}

So, how would you use this in practice?

/* reads a file into a buffer, prints the buffer contents on the screen
using get_text_line(), cleans up after itself */
unsigned check_read_file_function(void) {
FILE *test_file;
char filename[32];
char *file_buffer=NULL;

printf("\nEnter file name: ");
gets(filename);

if((test_file=fopen(filename,"rt"))==NULL) {
fprintf(stderr,"Can't open test file %s\n",filename);
return FALSE;
}

if(!(read_file_to_buffer(test_file,&file_buffer))) {
printf("\nCouldn't read test file to buffer");
fclose(test_file);
free(file_buffer);
file_buffer=NULL;
return FALSE;
}

fclose(test_file);

/* print the file from the buffer to the screen */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE))!=ENDOFTEXT)
puts(test_line_buf);

free(file_buffer);
file_buffer=NULL;

return TRUE;
}

And yes, Virginia, you do have to free the buffer your own self, close
your file, etc. Other uses of the function are up to the imagination of
the reader...

---
William Ernest Reid

Sep 17 '06 #11

P: n/a
Bill Reid wrote:
CBFalconer <cb********@yahoo.comwrote in message
.... snip ...
>
>I suggest you try ggets, which is written in pure standard C, and
is available at:

<http://cbfalconer.home.att.net/download/>

OK, for the sake of discussion, replacing fgets() with some type
of equivalent function where you START with a unopened file really
doesn't get you much, EXCEPT when you want to do interactive editing
of the file contents (fgets() is fine for general parsing and
searching), and in that case you probably want something more than
an equivalent of the largely brain-dead fgets().
You obviously didn't download and try ggets. It is a replacement
for gets and fgets. It is not a clone. It has different
parameters and semantics.

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski
--
Posted via a free Usenet account from http://www.teranews.com

Sep 18 '06 #12

P: n/a

CBFalconer <cb********@yahoo.comwrote in message
news:45*************@yahoo.com...
Bill Reid wrote:
CBFalconer <cb********@yahoo.comwrote in message
... snip ...
I suggest you try ggets, which is written in pure standard C, and
is available at:

<http://cbfalconer.home.att.net/download/>
OK, for the sake of discussion, replacing fgets() with some type
of equivalent function where you START with a unopened file really
doesn't get you much, EXCEPT when you want to do interactive editing
of the file contents (fgets() is fine for general parsing and
searching), and in that case you probably want something more than
an equivalent of the largely brain-dead fgets().

You obviously didn't download and try ggets. It is a replacement
for gets and fgets. It is not a clone. It has different
parameters and semantics.
You're right, I didn't look at it, I was just perambulating on the
general pointlessness of opening a file, reading it to a buffer, then
using a simple work-alike for fgets() (and ftell(), fseek(), rewind()).

To further the pointlessness, I noticed that the comments and the
code I posted were a little "off", and also recognize that some people
might find it offensive to read perhaps hundreds of lines just to
reset the buffer position. So I fixed the nits and added an argument
to allow you to only set the position without reading the buffer, with
a couple new macros for mnemonics:

#define POSITION 0 /* don't get line, just position for next
*/
#define GETLINE 1 /* get the line at current position */

....

/* like fgets() except works on a text buffer rather than a file stream
each call gets next line in buffer, returns start of line that is read
so is also kind of like ftell(), if you used ftell() before each fgets()
you can also "rewind()" function by passing FIRSTLINE as "start"
and you can run an entire loop by passing NEXTLINE as "start"
last call for buffer gets nothing, returns ENDOFTEXT, function is reset
if you only want to set buffer position, pass POSITION as "operation"
if you want to actually get the line, pass GETLINE */
unsigned long get_text_line
(char *text_buf,char *line_buf,unsigned long start,unsigned operation) {
static unsigned long text_idx;
unsigned long line_start=text_idx;
unsigned line_idx=0;

if(start==FIRSTLINE) line_start=text_idx=FIRSTLINE;

else if(start!=NEXTLINE) line_start=text_idx=start;

if(operation==POSITION) return line_start;

while(line_idx<LINEMAX) {

line_buf[line_idx]=text_buf[text_idx];
if(text_buf[text_idx]=='\0') break;

if(text_buf[text_idx]=='\n') {
line_buf[line_idx]='\0';
text_idx++,line_idx++;
break;
}
text_idx++,line_idx++;
}

if(line_idx==0) {
text_idx=0;
return ENDOFTEXT;
}
else return line_start;
}

And here are some more examples of how you can use it:

unsigned check_read_file_function(void) {
FILE *test_file;
char choice[16];
char filename[32];
char *file_buffer=NULL;
char test_line_buf[LINEMAX];
unsigned long line_start=0,search_line,stop_line;

printf("\nEnter file name: ");
gets(filename);

if((test_file=fopen(filename,"rt"))==NULL) {
fprintf(stderr,"Can't open test file %s\n",filename);
return FALSE;
}

if(!(read_file_to_buffer(test_file,&file_buffer))) {
printf("\nCouldn't read test file to buffer");
fclose(test_file);
free(file_buffer);
file_buffer=NULL;
return FALSE;
}

fclose(test_file);

/* now read the whole thing */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing out file from buffer - press RETURN\n\n");
gets(choice);

/* now read the whole thing...AGAIN! */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing out file from buffer AGAIN - press
RETURN\n\n");
gets(choice);

/* now find a search string, and save the position */
while(search_line!=ENDOFTEXT) {
search_line=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
if((strncmp(test_line_buf,"mid-file line search",20))==0) break;
}

/* now position search string line again, but don't get it */
get_text_line(file_buffer,test_line_buf,search_lin e,POSITION);

/* now read and print the rest of the file */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing file down FROM search string - press
RETURN\n\n");
gets(choice);

/* find the search string again, and save the position */
while(search_line!=ENDOFTEXT) {
search_line=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
if((strncmp(test_line_buf,"mid-file line search",20))==0) {
stop_line=search_line;
break;
}
}

/* "rewind()" back to the first line, but don't get it */
line_start=
get_text_line(file_buffer,test_line_buf,FIRSTLINE, POSITION);

/* then print out all the lines up to the search string line */
line_start=FIRSTLINE;
while(line_start<stop_line) {
line_start=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
puts(test_line_buf);
}

printf("That was printing file down TO search string - press
RETURN\n\n");
gets(choice);

free(file_buffer);
file_buffer=NULL;

return TRUE;
}

As I said, this is really only useful for some simple parsing of buffers
that may have come from someplace other than a file, such as perhaps
downloaded from the Internet...

---
William Ernest Reid

Sep 19 '06 #13

P: n/a
Thank you all so much for helping me out.
I have struggling with this problem for the past 4 months.

Bill Reid wrote:
CBFalconer <cb********@yahoo.comwrote in message
news:45*************@yahoo.com...
Bill Reid wrote:
CBFalconer <cb********@yahoo.comwrote in message
>
... snip ...
>
>I suggest you try ggets, which is written in pure standard C, and
>is available at:
>>
> <http://cbfalconer.home.att.net/download/>
>
OK, for the sake of discussion, replacing fgets() with some type
of equivalent function where you START with a unopened file really
doesn't get you much, EXCEPT when you want to do interactive editing
of the file contents (fgets() is fine for general parsing and
searching), and in that case you probably want something more than
an equivalent of the largely brain-dead fgets().
You obviously didn't download and try ggets. It is a replacement
for gets and fgets. It is not a clone. It has different
parameters and semantics.
You're right, I didn't look at it, I was just perambulating on the
general pointlessness of opening a file, reading it to a buffer, then
using a simple work-alike for fgets() (and ftell(), fseek(), rewind()).

To further the pointlessness, I noticed that the comments and the
code I posted were a little "off", and also recognize that some people
might find it offensive to read perhaps hundreds of lines just to
reset the buffer position. So I fixed the nits and added an argument
to allow you to only set the position without reading the buffer, with
a couple new macros for mnemonics:

#define POSITION 0 /* don't get line, just position for next
*/
#define GETLINE 1 /* get the line at current position */

...

/* like fgets() except works on a text buffer rather than a file stream
each call gets next line in buffer, returns start of line that is read
so is also kind of like ftell(), if you used ftell() before each fgets()
you can also "rewind()" function by passing FIRSTLINE as "start"
and you can run an entire loop by passing NEXTLINE as "start"
last call for buffer gets nothing, returns ENDOFTEXT, function is reset
if you only want to set buffer position, pass POSITION as "operation"
if you want to actually get the line, pass GETLINE */
unsigned long get_text_line
(char *text_buf,char *line_buf,unsigned long start,unsigned operation) {
static unsigned long text_idx;
unsigned long line_start=text_idx;
unsigned line_idx=0;

if(start==FIRSTLINE) line_start=text_idx=FIRSTLINE;

else if(start!=NEXTLINE) line_start=text_idx=start;

if(operation==POSITION) return line_start;

while(line_idx<LINEMAX) {

line_buf[line_idx]=text_buf[text_idx];
if(text_buf[text_idx]=='\0') break;

if(text_buf[text_idx]=='\n') {
line_buf[line_idx]='\0';
text_idx++,line_idx++;
break;
}
text_idx++,line_idx++;
}

if(line_idx==0) {
text_idx=0;
return ENDOFTEXT;
}
else return line_start;
}

And here are some more examples of how you can use it:

unsigned check_read_file_function(void) {
FILE *test_file;
char choice[16];
char filename[32];
char *file_buffer=NULL;
char test_line_buf[LINEMAX];
unsigned long line_start=0,search_line,stop_line;

printf("\nEnter file name: ");
gets(filename);

if((test_file=fopen(filename,"rt"))==NULL) {
fprintf(stderr,"Can't open test file %s\n",filename);
return FALSE;
}

if(!(read_file_to_buffer(test_file,&file_buffer))) {
printf("\nCouldn't read test file to buffer");
fclose(test_file);
free(file_buffer);
file_buffer=NULL;
return FALSE;
}

fclose(test_file);

/* now read the whole thing */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing out file from buffer - press RETURN\n\n");
gets(choice);

/* now read the whole thing...AGAIN! */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing out file from buffer AGAIN - press
RETURN\n\n");
gets(choice);

/* now find a search string, and save the position */
while(search_line!=ENDOFTEXT) {
search_line=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
if((strncmp(test_line_buf,"mid-file line search",20))==0) break;
}

/* now position search string line again, but don't get it */
get_text_line(file_buffer,test_line_buf,search_lin e,POSITION);

/* now read and print the rest of the file */
while((get_text_line(file_buffer,test_line_buf,NEX TLINE,GETLINE))
!=ENDOFTEXT)
puts(test_line_buf);

printf("That was printing file down FROM search string - press
RETURN\n\n");
gets(choice);

/* find the search string again, and save the position */
while(search_line!=ENDOFTEXT) {
search_line=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
if((strncmp(test_line_buf,"mid-file line search",20))==0) {
stop_line=search_line;
break;
}
}

/* "rewind()" back to the first line, but don't get it */
line_start=
get_text_line(file_buffer,test_line_buf,FIRSTLINE, POSITION);

/* then print out all the lines up to the search string line */
line_start=FIRSTLINE;
while(line_start<stop_line) {
line_start=
get_text_line(file_buffer,test_line_buf,NEXTLINE,G ETLINE);
puts(test_line_buf);
}

printf("That was printing file down TO search string - press
RETURN\n\n");
gets(choice);

free(file_buffer);
file_buffer=NULL;

return TRUE;
}

As I said, this is really only useful for some simple parsing of buffers
that may have come from someplace other than a file, such as perhaps
downloaded from the Internet...

---
William Ernest Reid
Sep 19 '06 #14

P: n/a
FireHead wrote:
>
Hello C World & Fanatics

I am trying replace fgets and provide a equavivalant function
I'm using line_to_string these days.

/* BEGIN type_1.c */

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

#define ARGV_0 "type_1"

struct list_node {
struct list_node *next;
void *data;
};

int line_to_string(FILE *fp, char **line, size_t *size);
void list_free(struct list_node *node, void (*free_data)(void *));
int list_fputs(FILE *stream, struct list_node *node);
struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data);

int main(int argc, char *argv[])
{
int rc;
FILE *fd;
char *buff_ptr;
size_t buff_size;
struct list_node *head, *tail;

tail = head = NULL;
buff_size = 0;
buff_ptr = NULL;
if (argc 1) {
while (*++argv != NULL) {
fd = fopen(*argv, "r");
if (fd != NULL) {
while ((rc = line_to_string
(fd, &buff_ptr, &buff_size)) 0)
{
tail = string_node(&head, tail, buff_ptr);
if (tail == NULL) {
break;
}
}
fclose(fd);
switch (rc) {
case EOF:
if (buff_ptr != NULL
&& strlen(buff_ptr) 0)
{
puts("rc equals EOF\n"
"The string in buff_ptr is:");
puts(buff_ptr);
}
break;
case 0:
puts("realloc returned a null pointer "
"value in line_to_string.");
if (buff_size 1) {
puts("rc equals 0\n"
"The string in buff_ptr is:");
puts(buff_ptr);
}
break;
default:
puts("malloc problem in string_node.");
break;
}
} else {
fprintf(stderr,
"\nfopen() problem with \"%s\"\n", *argv);
break;
}
list_fputs(stdout, head);
list_free(head, free);
head = NULL;
}
free(buff_ptr);
} else {
puts(
"Usage:\n>" ARGV_0
" <FILE_0.txt<FILE_1.txt<FILE_2.txt...\n"
);
}
return 0;
}

int line_to_string(FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;

count = 0;
while ((rc = getc(fp)) != EOF) {
++count;
if (count + 2 *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size count) {
(*line)[count] = '\0';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == '\n') {
(*line)[count - 1] = '\0';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count INT_MAX ? INT_MAX : count;
} else {
if (*size count) {
(*line)[count] = '\0';
}
}
return rc;
}

void list_free(struct list_node *node, void (*free_data)(void *))
{
struct list_node *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

int list_fputs(FILE *stream, struct list_node *node)
{
while (node != NULL) {
if (fputs(node -data, stream) == EOF
|| putc('\n', stream) == EOF) {
return EOF;
}
node = node -next;
}
return 0;
}

struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data)
{
struct list_node *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(strlen(data) + 1);
if (node -data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -next = node;
}
strcpy(node -data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

/* END type_1.c */
--
pete
Sep 20 '06 #15

P: n/a
Hello C Fanatics

After a look for R&D I am trying the combine Pete(s) algorithm code and
I think it was Bill Reid(s) code.

As a dumb user:
I want use code in the following

while( feof( File_Pointer) == EXIT_SUCCESS){
if( read_Line( File_Pointer, returned_buffer)
printf("%s", returned_buffer);
}

I do not want to call the function free() outside the loop or inside
the loop.

Another pointer:

if I had a function like so:

short read_Line(FILE *file_pointer, char** returned_buffer){

char * buffer = "Rules";
..... how I can replace the pointer of chars pointed at returned_buffer
with buffer?
}

How can I acheive the below coding style?
char *new_buffer = "Science Fiction";
read_Line(File_Pointer, &new_buffer);
printf("%s", new_buffer);

and I expect the result like so: "Rules".
I really think it should be possible (90%) to using fgets.
Hope this clarifies the main point of this forum.

Sep 22 '06 #16

P: n/a
"FireHead" <sa************@htech.health.nsw.gov.auwrites:
After a look for R&D I am trying the combine Pete(s) algorithm code and
I think it was Bill Reid(s) code.

As a dumb user:
I want use code in the following

while( feof( File_Pointer) == EXIT_SUCCESS){
if( read_Line( File_Pointer, returned_buffer)
printf("%s", returned_buffer);
}
[...]

EXIT_SUCCESS doesn't mean what you think it means.

The feof() function returns a true or false value; non-zero if the
end-of-file indicator is set, zero if it isn't. EXIT_SUCCESS is
a macro that expands to an integer expression that can be used as
an argument to the exit() function or as a value to be returned
from the main() function; it shouldn't be used for anything else.
In particular, EXIT_SUCCESS typically (and perhaps on all actual
implementations) happens to have the value 0, so your test will
probably work, but it's obfuscated and it will fail if EXIT_SUCCESS != 0.

A better and clearer way to use the feof() function is:

while (! feof(File_Pointer)) {
...
}

An even better way is not to use the feof() function at all. feof()
becomes true *after* an attempt to read from a file has failed. Most
of the standard functions that read from files return a special value,
typically EOF, to indicate that they've encountered either the end of
the file or an error condition. You should control your loop by
checking that return value. You can use the feof() function *after* a
read has failed, to find out whether it did so because it reached the
end of the file or encountered an error.

Also, if an attempt to read from a file fails because of an error
rather than reaching the end of the file, feof() will return false,
and you'll have an infinite loop.

See the comp.lang.c FAQ, <http://www.c-faq.com/>, question 12.2.

--
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.
Sep 22 '06 #17

P: n/a
Hello,
After the evaluation for the EXIT_SUCCESS; it turns out that the value
of EXIT_SUCCESS < IS 0 and EXIT_FAILURE accordingly.

You should be able to see the physical value of
EXIT_SUCCESS/EXIT_FAILURE in the stdio.h header file where it is
defined.

I have to first check whether the file has reached the end of the file
which is what the function feof() does.

And also even using a function such as fgets() I have not had any
disclarification(s) when I use the function fgets() and feof().

As of now I am not really worried about feof() at this moment of the
dev stage yet.
Keith Thompson wrote:
"FireHead" <sa************@htech.health.nsw.gov.auwrites:
After a look for R&D I am to trying the combine Pete(s) algorithm code and
I think it was Bill Reid(s) code.

As a dumb user:
I want use code in the following

while( feof( File_Pointer) == EXIT_SUCCESS){
if( read_Line( File_Pointer, returned_buffer)
printf("%s", returned_buffer);
}
[...]

EXIT_SUCCESS doesn't mean what you think it means.

The feof() function returns a true or false value; non-zero if the
end-of-file indicator is set, zero if it isn't. EXIT_SUCCESS is
a macro that expands to an integer expression that can be used as
an argument to the exit() function or as a value to be returned
from the main() function; it shouldn't be used for anything else.
In particular, EXIT_SUCCESS typically (and perhaps on all actual
implementations) happens to have the value 0, so your test will
probably work, but it's obfuscated and it will fail if EXIT_SUCCESS != 0.

A better and clearer way to use the feof() function is:

while (! feof(File_Pointer)) {
...
}

An even better way is not to use the feof() function at all. feof()
becomes true *after* an attempt to read from a file has failed. Most
of the standard functions that read from files return a special value,
typically EOF, to indicate that they've encountered either the end of
the file or an error condition. You should control your loop by
checking that return value. You can use the feof() function *after* a
read has failed, to find out whether it did so because it reached the
end of the file or encountered an error.

Also, if an attempt to read from a file fails because of an error
rather than reaching the end of the file, feof() will return false,
and you'll have an infinite loop.

See the comp.lang.c FAQ, <http://www.c-faq.com/>, question 12.2.

--
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.
Sep 23 '06 #18

P: n/a
Please don't top-post. See <http://www.caliburn.nl/topposting.html>
and <http://www.cpax.org.uk/prg/writings/topposting.php>.

"FireHead" <sa************@htech.health.nsw.gov.auwrites:
Keith Thompson wrote:
>"FireHead" <sa************@htech.health.nsw.gov.auwrites:
After a look for R&D I am to trying the combine Pete(s) algorithm code and
I think it was Bill Reid(s) code.

As a dumb user:
I want use code in the following

while( feof( File_Pointer) == EXIT_SUCCESS){
if( read_Line( File_Pointer, returned_buffer)
printf("%s", returned_buffer);
}
[...]

EXIT_SUCCESS doesn't mean what you think it means.
[...]
>
After the evaluation for the EXIT_SUCCESS; it turns out that the value
of EXIT_SUCCESS < IS 0 and EXIT_FAILURE accordingly.

You should be able to see the physical value of
EXIT_SUCCESS/EXIT_FAILURE in the stdio.h header file where it is
defined.
Yes, I'm sure it is. That's not the point. Comparing the result of
feof() to EXIT_SUCCESS might happen to work by accident, but it's very
bad style.

If you wanted to check whether s is an empty string, would you write
"strlen(s) == EXIT_SUCCESS"? It happens to work, but it doesn't make
sense.
I have to first check whether the file has reached the end of the file
which is what the function feof() does.

And also even using a function such as fgets() I have not had any
disclarification(s) when I use the function fgets() and feof().

As of now I am not really worried about feof() at this moment of the
dev stage yet.
You don't want to use feof(). Read section 12 of the FAQ,
<http://www.c-faq.com/>

--
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.
Sep 23 '06 #19

P: n/a
Hello All,

My original topic should have been " using/replace fgets".

I think i have finally solved and used fgets in my program.
But I see somewhere bug/memory leak I just am not able pin the memory
leak.
Could anybody assist me in this issue please.

The this the code that I have managed to get it working.
//-------------------------------------------------------------------------------------------------------------------------------------------------//
/*
Will BE MULTITHREADED
open a original file (source file)
Look for the existing custom folder in the HOME directory
If the HOME directory does not exist
Then see if the specs exists in the /usr/local/share (Default)
If the /usr/local/share does not exist then create a template
create a temp
*/

#include <cliargs.h>
short readPreLine(FILE* pSource,char **content);
short readPostLine(FILE* pSource,char **content);
short readLPostLine(FILE *pSource,char** content,int default_length);
short readLPreLine(FILE *pSource,char** content,int default_length);
char* get_Copy(char* pStr);

char* get_Copy(char* pStr){
u_int8_t *temp =0;
u_int8_t *final =0;
u_int8_t byte = 0;
u_int8_t dummy = 0;
temp = pStr;
int pos = 0;
final = &dummy;
/*initilize the contents with new address*/
do{
byte = *temp;printf("%c",byte);
final++;
temp++;
}while(byte!='\0');
*final = '\0';

temp = "";
temp = pStr;
/*clean up everything*/

char *results = "";
results = strcpy( final,temp);

return results;
}
/*
short get_Stream(FILE* pSource,char* result){
size_t buflen = 0;
char offset= 0;
int ret=EXIT_SUCCESS;
fpos_t* pCurPos=0 ; //current file position
fpos_t* pOldPos=0 ; //old file position
char *finally = "";
char *buffer = 0;
//get the starting File pointer position
fgetpos(pSource,&pOldPos);
//find the newline = 0x13
do{offset = 0; offset=fgetc(pSource);
} while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL &&
offset!=0xFF);

//get the Current File position
fgetpos (pSource,&pCurPos);
printf("%u",pCurPos);
//Total Buffer Length
buflen = (size_t)pCurPos - (size_t)pOldPos;
if(( offset == 0xFF || offset == EOF || offset==NULL) && (buflen ==
EXIT_FAILURE || buflen == EXIT_SUCCESS))
ret= EXIT_FAILURE;
else{
//Reset Everything
fsetpos (pSource,&pOldPos);
//allocate memory for the new address register
buffer = (char *)malloc(buflen);
//read file buffer using fgets
fgets(buffer,buflen,pSource);
//copy the string to a automatic variable register
//finally = get_Copy(buffer);
printf("\nfeof = %d\n",strlen(buffer));

//free the contents
free(buffer);

ret=EXIT_SUCCESS;
}//ELSE

buffer=0;
pCurPos = 0;
pOldPos = 0;
offset = 0;
return ret;
}*/

int malloc_length(char* source_buffer){
int offset=0;
for(offset = 0;source_buffer[offset]!=NULL || source_buffer[offset]!=0
|| source_buffer[offset]!='\0';offset++);
return offset;
}

short readLPostLine(FILE *pSource,char** content,int default_length){
short ret=EXIT_SUCCESS;
int return_length;return_length = 0;
char* currentline;currentline = 0;
char* returnline;returnline = 0;
char* duplicate;duplicate = 0;
char offset;offset = 0;
int temp_length = 0;
return_length = return_length+default_length;
/* allocate default sized buffer */
currentline = (char*)malloc(default_length);
currentline = strcpy(currentline,"");
/*allocate memory temporarily*/
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,"");
do{
/* read the the line first*/
if((currentline=fgets(currentline,default_length+1 ,pSource))
!=NULL){
offset = (char)(strlen(currentline) 0 ?
currentline[strlen(currentline)-1]: 0 );
if(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF) && offset!=NULL){
temp_length = strlen(returnline);
if(temp_length == (return_length+default_length) ||
temp_length == return_length ){
return_length = return_length+default_length;
duplicate =(char*)malloc(return_length+default_length);
duplicate = strcpy(duplicate,returnline);
free(returnline);returnline=0;
return_length = return_length+default_length;
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,duplicate);
free(duplicate);duplicate=0;
}
if(temp_length == 0) returnline = strcpy(returnline,currentline);
else returnline = strcat(returnline,currentline);
}else{
returnline = strncat(returnline,currentline,strlen(currentline)-1);
ret = EXIT_SUCCESS;
}
}/* Main IF */
else
ret = EXIT_FAILURE;
}while(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF)
&& ret==EXIT_SUCCESS);

/* end of while*/
if(offset == 0x0A||offset == 0x0D ){
*content = malloc(strlen(returnline)+1);
*content = strcpy(*content,returnline);
ret = EXIT_SUCCESS;
}else
ret = EXIT_FAILURE;

free(currentline);
free(returnline);

return ret;
}

short readLPreLine(FILE *pSource,char** content,int default_length){
short ret=EXIT_SUCCESS;
int return_length;return_length = 0;
char* currentline;currentline = 0;

char* returnline;returnline = 0;
char* duplicate;duplicate = 0;
char offset;offset = 0;
int temp_length = 0;
return_length = return_length+default_length;
/* allocate default sized buffer */
currentline = (char*)malloc(default_length);
currentline = strcpy(currentline,"");
/*allocate memory temporarily*/
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,"");
/* read the the line first*/
currentline = fgets(currentline,default_length+1,pSource);
if(currentline!=NULL){
offset = (strlen(currentline) 0?
currentline[strlen(currentline)-1]: EOF);
if(offset!=0&&offset!=0xFF&&offset!=EOF){
while(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF)){
temp_length = strlen(returnline);
if(temp_length == (return_length+default_length) ||
temp_length == return_length ){
return_length = return_length+default_length;
duplicate =(char*)malloc(return_length+default_length);
duplicate = strcpy(duplicate,returnline);
free(returnline);returnline=0;
return_length = return_length+default_length;
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,duplicate);
free(duplicate);duplicate=0;
}/* if */
returnline = strcat(returnline,currentline);
/*read the file again */
currentline = fgets(currentline,default_length+1,pSource);
offset = currentline[strlen(currentline)-1];
}/*while*/
if(offset == 0x0A||offset == 0x0D || offset == 0 || offset ==
EOF){

if( strlen(returnline)==0)
returnline = strncpy(returnline,currentline,strlen(currentline) +1);
else
returnline = strncat(returnline,currentline,strlen(currentline)-1);

ret = EXIT_SUCCESS; }
}else
ret = EXIT_FAILURE;
}else ret = EXIT_FAILURE;

if(ret == EXIT_SUCCESS){
*content = malloc(strlen(returnline)+1);
*content = strcpy(*content,returnline);
}
free(currentline);
free(returnline);
return ret;
}

short readPreLine(FILE* pSource,char **content){
return readLPreLine(pSource,content,512); /* default UNIX length */
}

short readPostLine(FILE* pSource,char **content){
return readLPostLine(pSource,content,512); /* default UNIX length
*/
}

int main(int argc,const char* argv[])
{
FILE* pSourceFile;
const char* ATOMIC_NAME;
char* ret = 0;
ATOMIC_NAME = "/etc/samba/smb.conf";
printf("%s\n",ATOMIC_NAME);
pSourceFile = fopen(ATOMIC_NAME,"rb");

if(pSourceFile==NULL){
printf("File not found\n");
exit(EXIT_FAILURE);
}
else
fseek(pSourceFile,SEEK_SET,SEEK_SET);

while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
fclose(pSourceFile);

}
//-------------------------------------------------------------------------------------------------------------------------------------------//
In the following code:
while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
How can I avoid calling < free(ret) ?

Thanks guys & girls ( if any).

Oct 2 '06 #20

P: n/a
Hello All,

My original topic should have been " using/replace fgets".

I think i have finally solved and used fgets in my program.
But I see somewhere bug/memory leak I just am not able pin the memory
leak.
Could anybody assist me in this issue please.

This can be anybody for any reason.
This code will now offically become part of the Public Domain.

The this the code that I have managed to get it working.
//-------------------------------------------------------------------------------------------------------------------------------------------------//
/*
Will BE MULTITHREADED
open a original file (source file)
Look for the existing custom folder in the HOME directory
If the HOME directory does not exist
Then see if the specs exists in the /usr/local/share (Default)
If the /usr/local/share does not exist then create a template
create a temp
*/

#include <cliargs.h>
short readPreLine(FILE* pSource,char **content);
short readPostLine(FILE* pSource,char **content);
short readLPostLine(FILE *pSource,char** content,int default_length);
short readLPreLine(FILE *pSource,char** content,int default_length);
char* get_Copy(char* pStr);

char* get_Copy(char* pStr){
u_int8_t *temp =0;
u_int8_t *final =0;
u_int8_t byte = 0;
u_int8_t dummy = 0;
temp = pStr;
int pos = 0;
final = &dummy;
/*initilize the contents with new address*/
do{
byte = *temp;printf("%c",byte);
final++;
temp++;
}while(byte!='\0');
*final = '\0';

temp = "";
temp = pStr;
/*clean up everything*/

char *results = "";
results = strcpy( final,temp);

return results;
}
/*
short get_Stream(FILE* pSource,char* result){
size_t buflen = 0;
char offset= 0;
int ret=EXIT_SUCCESS;
fpos_t* pCurPos=0 ; //current file position
fpos_t* pOldPos=0 ; //old file position
char *finally = "";
char *buffer = 0;
//get the starting File pointer position
fgetpos(pSource,&pOldPos);
//find the newline = 0x13
do{offset = 0; offset=fgetc(pSource);
} while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL &&
offset!=0xFF);

//get the Current File position
fgetpos (pSource,&pCurPos);
printf("%u",pCurPos);
//Total Buffer Length
buflen = (size_t)pCurPos - (size_t)pOldPos;
if(( offset == 0xFF || offset == EOF || offset==NULL) && (buflen ==
EXIT_FAILURE || buflen == EXIT_SUCCESS))
ret= EXIT_FAILURE;
else{
//Reset Everything
fsetpos (pSource,&pOldPos);
//allocate memory for the new address register
buffer = (char *)malloc(buflen);
//read file buffer using fgets
fgets(buffer,buflen,pSource);
//copy the string to a automatic variable register
//finally = get_Copy(buffer);
printf("\nfeof = %d\n",strlen(buffer));

//free the contents
free(buffer);

ret=EXIT_SUCCESS;
}//ELSE

buffer=0;
pCurPos = 0;
pOldPos = 0;
offset = 0;
return ret;
}*/

int malloc_length(char* source_buffer){
int offset=0;
for(offset = 0;source_buffer[offset]!=NULL || source_buffer[offset]!=0
|| source_buffer[offset]!='\0';offset++);
return offset;
}

short readLPostLine(FILE *pSource,char** content,int default_length){
short ret=EXIT_SUCCESS;
int return_length;return_length = 0;
char* currentline;currentline = 0;
char* returnline;returnline = 0;
char* duplicate;duplicate = 0;
char offset;offset = 0;
int temp_length = 0;
return_length = return_length+default_length;
/* allocate default sized buffer */
currentline = (char*)malloc(default_length);
currentline = strcpy(currentline,"");
/*allocate memory temporarily*/
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,"");
do{
/* read the the line first*/
if((currentline=fgets(currentline,default_length+1 ,pSource))
!=NULL){
offset = (char)(strlen(currentline) 0 ?
currentline[strlen(currentline)-1]: 0 );
if(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF) && offset!=NULL){
temp_length = strlen(returnline);
if(temp_length == (return_length+default_length) ||
temp_length == return_length ){
return_length = return_length+default_length;
duplicate =(char*)malloc(return_length+default_length);
duplicate = strcpy(duplicate,returnline);
free(returnline);returnline=0;
return_length = return_length+default_length;
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,duplicate);
free(duplicate);duplicate=0;
}
if(temp_length == 0) returnline = strcpy(returnline,currentline);
else returnline = strcat(returnline,currentline);
}else{
returnline = strncat(returnline,currentline,strlen(currentline)-1);
ret = EXIT_SUCCESS;
}
}/* Main IF */
else
ret = EXIT_FAILURE;
}while(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF)
&& ret==EXIT_SUCCESS);

/* end of while*/
if(offset == 0x0A||offset == 0x0D ){
*content = malloc(strlen(returnline)+1);
*content = strcpy(*content,returnline);
ret = EXIT_SUCCESS;
}else
ret = EXIT_FAILURE;

free(currentline);
free(returnline);

return ret;
}

short readLPreLine(FILE *pSource,char** content,int default_length){
short ret=EXIT_SUCCESS;
int return_length;return_length = 0;
char* currentline;currentline = 0;

char* returnline;returnline = 0;
char* duplicate;duplicate = 0;
char offset;offset = 0;
int temp_length = 0;
return_length = return_length+default_length;
/* allocate default sized buffer */
currentline = (char*)malloc(default_length);
currentline = strcpy(currentline,"");
/*allocate memory temporarily*/
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,"");
/* read the the line first*/
currentline = fgets(currentline,default_length+1,pSource);
if(currentline!=NULL){
offset = (strlen(currentline) 0?
currentline[strlen(currentline)-1]: EOF);
if(offset!=0&&offset!=0xFF&&offset!=EOF){
while(offset != 0x0A && offset!=0x0D &&
(offset!=0&&offset!=0xFF&&offset!=EOF)){
temp_length = strlen(returnline);
if(temp_length == (return_length+default_length) ||
temp_length == return_length ){
return_length = return_length+default_length;
duplicate =(char*)malloc(return_length+default_length);
duplicate = strcpy(duplicate,returnline);
free(returnline);returnline=0;
return_length = return_length+default_length;
returnline = (char*)malloc(return_length+default_length);
returnline = strcpy(returnline,duplicate);
free(duplicate);duplicate=0;
}/* if */
returnline = strcat(returnline,currentline);
/*read the file again */
currentline = fgets(currentline,default_length+1,pSource);
offset = currentline[strlen(currentline)-1];
}/*while*/
if(offset == 0x0A||offset == 0x0D || offset == 0 || offset ==
EOF){

if( strlen(returnline)==0)
returnline = strncpy(returnline,currentline,strlen(currentline) +1);
else
returnline = strncat(returnline,currentline,strlen(currentline)-1);

ret = EXIT_SUCCESS; }
}else
ret = EXIT_FAILURE;
}else ret = EXIT_FAILURE;

if(ret == EXIT_SUCCESS){
*content = malloc(strlen(returnline)+1);
*content = strcpy(*content,returnline);
}
free(currentline);
free(returnline);
return ret;
}

short readPreLine(FILE* pSource,char **content){
return readLPreLine(pSource,content,512); /* default UNIX length */
}

short readPostLine(FILE* pSource,char **content){
return readLPostLine(pSource,content,512); /* default UNIX length
*/
}

int main(int argc,const char* argv[])
{
FILE* pSourceFile;
const char* ATOMIC_NAME;
char* ret = 0;
ATOMIC_NAME = "/etc/samba/smb.conf";
printf("%s\n",ATOMIC_NAME);
pSourceFile = fopen(ATOMIC_NAME,"rb");

if(pSourceFile==NULL){
printf("File not found\n");
exit(EXIT_FAILURE);
}
else
fseek(pSourceFile,SEEK_SET,SEEK_SET);

while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
fclose(pSourceFile);

}
//-------------------------------------------------------------------------------------------------------------------------------------------//
In the following code:
while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
How can I avoid calling < free(ret) ?

Thanks guys & girls ( if any).

Oct 2 '06 #21

P: n/a
[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]

FireHead said:

<snip>
>
In the following code:
while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
How can I avoid calling < free(ret) ?
You seem to be asking "how can I get my line-reading routine to re-use an
existing buffer rather than allocate a fresh one from scratch on each
call?"

If that is indeed your question, the answer is very simple. Simply rewrite
the routine to do what you want. In this case, the only problem you have is
one of communicating the existing buffer size to the function. The fix here
is to pass a size_t *. You set up a size_t with value 0, and pass its
address to the function. On return, it has the buffer size. On subsequent
calls, you pass this buffer size in, so that the function knows how much it
can write before it has to start allocating.

http://www.cpax.org.uk/prg/writings/fgetdata.php discusses this problem and
provides simple source code that solves it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 2 '06 #22

P: n/a
Richard Heathfield wrote:
[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]
You seem to be asking "how can I get my line-reading routine to re-use an
existing buffer rather than allocate a fresh one from scratch on each
call?"
I thought for sure, Richard, that you would just slaughter this guy for
multiple code violations, but I'm pleasantly surprised.

As far as the code goes, it already infers unix-isms (mention of /usr/local),
in which case, if there is no particular reason for using stdio for this
(i.e. the wheel is not being rewritten for a reason), I seriously suggest use
of posix mmap() here. IMO, stdio is just not made for this type of activity -
whereas mmap() was. Other than that, it's very hard to read, is nowhere near
modular enough, and makes plenty of non-portable assumptions and redundant
logic checks (!= 0 vs != '\0').

At the risk of getting beat down in comp.lang.c for a posix recommendation,
please use mmap() or at the minimum: rewrite it all again.
Oct 2 '06 #23

P: n/a
Richard Heathfield wrote:
[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]

FireHead said:

<snip>

In the following code:
while(readPostLine(pSourceFile,&ret)==EXIT_SUCCESS ){
printf("%s\n",ret);
free(ret);
}
How can I avoid calling < free(ret) ?

You seem to be asking "how can I get my line-reading routine to re-use an
existing buffer rather than allocate a fresh one from scratch on each
call?"

If that is indeed your question, the answer is very simple. Simply rewrite
the routine to do what you want. In this case, the only problem you have is
one of communicating the existing buffer size to the function. The fix here
is to pass a size_t *. You set up a size_t with value 0, and pass its
address to the function. On return, it has the buffer size. On subsequent
calls, you pass this buffer size in, so that the function knows how much it
can write before it has to start allocating.

http://www.cpax.org.uk/prg/writings/fgetdata.php discusses this problem and
provides simple source code that solves it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)

The file < config.h contains the following header file declartion.
#ifndef COMMON_HEADER_FILES
#define COMMON_HEADER_FILES
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <regex.h>
#include <time.h>
#include <sys/mman.h>
#include <fcntl.h>
#endif
I should have put the standard header files instead .. oops.

Oct 2 '06 #24

P: n/a
Christopher Layne said:
Richard Heathfield wrote:
>[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]
You seem to be asking "how can I get my line-reading routine to re-use an
existing buffer rather than allocate a fresh one from scratch on each
call?"

I thought for sure, Richard, that you would just slaughter this guy for
multiple code violations, but I'm pleasantly surprised.
Yeah, I just slaughtered him for *one*, because the one was a showstopper.
:-)

Seriously, the word "slaughter" indicates that you think a code critique is
an attack. It isn't. It's an attempt to educate the author. If he takes it
in that vein, he will learn a lot. That's certainly my hope.
As far as the code goes, it already infers unix-isms (mention of
/usr/local), in which case, if there is no particular reason for using
stdio for this
There's no particular reason why he shouldn't use a generally portable
technique for doing something as general-purpose and non-platform-specific
as reading a complete line from a stream, rather than nail his routines to
a particular implementation.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 2 '06 #25

P: n/a
FireHead said:
Richard Heathfield wrote:
>[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]
<snip>
The file < config.h >
....er, I didn't even see a <config.h- the only inclusion I saw was of a
<cliargs.h>
contains the following header file declartion.
#ifndef COMMON_HEADER_FILES
#define COMMON_HEADER_FILES
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <regex.h>
#include <time.h>
#include <sys/mman.h>
#include <fcntl.h>
#endif
(Four of which are not standard C headers.)
I should have put the standard header files instead .. oops.
Yeah, especially when posting in comp.lang.c it's a good idea to reduce your
problem to one that can be expressed using only standard C constructs - or,
at the very least, to special-plead "I know this has got Unixy stuff in it,
but please just ignore all that stuff and focus on the C bit", or even "I'm
not sure whether this is a C problem or a Unix problem, here's the problem,
here's the code, what do you reckon?"

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 2 '06 #26

P: n/a
Richard Heathfield wrote:
>[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]
<snip>
The file < config.h >
....er, I didn't even see a <config.h- the only inclusion I saw was of
a
<cliargs.h>
contains the following header file declartion.
#ifndef COMMON_HEADER_FILES
#define COMMON_HEADER_FILES
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <regex.h>
#include <time.h>
#include <sys/mman.h>
#include <fcntl.h>
#endif
(Four of which are not standard C headers.)
I should have put the standard header files instead .. oops.
>Yeah, especially when posting in comp.lang.c it's a good idea to reduce your
problem to one that can be expressed using only standard C constructs - or,
at the very least, to special-plead "I know this has got Unixy stuff in it,
but please just ignore all that stuff and focus on the C bit", or even "I'm
not sure whether this is a C problem or a Unix problem, here's the problem,
here's the code, what do you reckon?"
//---------------------------------------------------------------------------------------------------------//
Just a pointer the config.h supposed to cliargs.h header file.

In terms of portablilty anybody should be able these codes.

When the fopen is called rather that /usr/local/some_file_name it can
be also be used for any platform as long as you give valid folder/file
path.
For windows it can be < fopen( "Window File Name");

then code that I have currently will still work for any platform.

One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.
But I just keep gets blasted Segmentation Error/ Memory out of range.

By using get_Copy I might be able simply code even further.

You all might have noticed that I have 3 version of the same
functionality.

2 function will be portable for any platform.

The below function is clean and understandable but its not functionable
on SCO UNIX and on windows.
Now I will not include windows because Windows is just @##$@#$.

/*
short get_Stream(FILE* pSource,char* result){
size_t buflen = 0;
char offset= 0;
int ret=EXIT_SUCCESS;
fpos_t* pCurPos=0 ; //current file position
fpos_t* pOldPos=0 ; //old file position
char *finally = "";
char *buffer = 0;
//get the starting File pointer position
fgetpos(pSource,&pOldPos);
//find the newline = 0x13
do{offset = 0; offset=fgetc(pSource);
} while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL &&

offset!=0xFF);

//get the Current File position
fgetpos (pSource,&pCurPos);
printf("%u",pCurPos);
//Total Buffer Length
buflen = (size_t)pCurPos - (size_t)pOldPos;
if(( offset == 0xFF || offset == EOF || offset==NULL) && (buflen ==
EXIT_FAILURE || buflen == EXIT_SUCCESS))
ret= EXIT_FAILURE;
else{
//Reset Everything
fsetpos (pSource,&pOldPos);
//allocate memory for the new address register
buffer = (char *)malloc(buflen);
//read file buffer using fgets
fgets(buffer,buflen,pSource);
//copy the string to a automatic variable register
//finally = get_Copy(buffer);
printf("\nfeof = %d\n",strlen(buffer));

//free the contents
free(buffer);

ret=EXIT_SUCCESS;
}//ELSE

buffer=0;
pCurPos = 0;
pOldPos = 0;
offset = 0;
return ret;

}*/
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.

So to me this proverb equated to where < EXIT_SUCCESS = meant that the
function worked fine and have had no bugs and likewise EXIT_FAILURE
is the opposite of EXIT_SUCCESS.

Oct 2 '06 #27

P: n/a
Richard Heathfield wrote:
>[Lots of source, but it #included a non-standard header, so I couldn't
compile it for crits]
<snip>
The file < config.h >
....er, I didn't even see a <config.h- the only inclusion I saw was of
a
<cliargs.h>
contains the following header file declartion.
#ifndef COMMON_HEADER_FILES
#define COMMON_HEADER_FILES
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <regex.h>
#include <time.h>
#include <sys/mman.h>
#include <fcntl.h>
#endif
(Four of which are not standard C headers.)
I should have put the standard header files instead .. oops.
>Yeah, especially when posting in comp.lang.c it's a good idea to reduce your
problem to one that can be expressed using only standard C constructs - or,
at the very least, to special-plead "I know this has got Unixy stuff in it,
but please just ignore all that stuff and focus on the C bit", or even "I'm
not sure whether this is a C problem or a Unix problem, here's the problem,
here's the code, what do you reckon?"
//---------------------------------------------------------------------------------------------------------//
Just a pointer the config.h supposed to cliargs.h header file.

In terms of portablilty anybody should be able these codes.

When the fopen is called rather that /usr/local/some_file_name it can
be also be used for any platform as long as you give valid folder/file
path.
For windows it can be < fopen( "Window File Name");

then code that I have currently will still work for any platform.

One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.
But I just keep gets blasted Segmentation Error/ Memory out of range.

By using get_Copy I might be able simply code even further.

You all might have noticed that I have 3 version of the same
functionality.

2 function will be portable for any platform.

The below function is clean and understandable but its not functionable
on SCO UNIX and on windows.
Now I will not include windows because Windows is just @##$@#$.

/*
short get_Stream(FILE* pSource,char* result){
size_t buflen = 0;
char offset= 0;
int ret=EXIT_SUCCESS;
fpos_t* pCurPos=0 ; //current file position
fpos_t* pOldPos=0 ; //old file position
char *finally = "";
char *buffer = 0;
//get the starting File pointer position
fgetpos(pSource,&pOldPos);
//find the newline = 0x13
do{offset = 0; offset=fgetc(pSource);
} while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL &&

offset!=0xFF);

//get the Current File position
fgetpos (pSource,&pCurPos);
printf("%u",pCurPos);
//Total Buffer Length
buflen = (size_t)pCurPos - (size_t)pOldPos;
if(( offset == 0xFF || offset == EOF || offset==NULL) && (buflen ==
EXIT_FAILURE || buflen == EXIT_SUCCESS))
ret= EXIT_FAILURE;
else{
//Reset Everything
fsetpos (pSource,&pOldPos);
//allocate memory for the new address register
buffer = (char *)malloc(buflen);
//read file buffer using fgets
fgets(buffer,buflen,pSource);
//copy the string to a automatic variable register
//finally = get_Copy(buffer);
printf("\nfeof = %d\n",strlen(buffer));

//free the contents
free(buffer);

ret=EXIT_SUCCESS;
}//ELSE

buffer=0;
pCurPos = 0;
pOldPos = 0;
offset = 0;
return ret;

}*/
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.

So to me this proverb equated to where < EXIT_SUCCESS = meant that the
function worked fine and have had no bugs and likewise EXIT_FAILURE
is the opposite of EXIT_SUCCESS.
Thanks for the help so far you have give me.

Oct 2 '06 #28

P: n/a
FireHead wrote:
In terms of portablilty anybody should be able these codes.
Not when it's a minotaur maze.
then code that I have currently will still work for any platform.
I don't know about that one, but I'm not going to argue it.
One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.
Well, the equiv is VirtualAlloc() on windows. Anyways, away from mmap()
and equivalents - it looks like your primary purpose is doing a bunch of
length/size management and appropriately returning a line without initial
buffer size having to be known - yet you force it all with:

return readLPreLine(pSource,content,512); /* default UNIX length */

Why bother with all the other crap if you're maxing out at 512??

size_t blah(char *d, size_t sz, FILE *f)
{
char buf[512];

if (fgets(buf, sizeof(buf), f) == NULL) {
/*
* this requires you to check " == (size_t)-1"
* the alternative is 0, which may not be accurate for your case
* or ssize_t (which is not ANSI, but POSIX) or just an int.
*/
return -1;
}

return (strlen(buf) - 1);
}

Or perhaps I'm misunderstanding your purpose - as it was fairly hard to
understand from looking at it.

Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.
The point of mmap() is to providely memory mapped files and to not have to
play around with copies of things unless you need the copies.
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.
There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).

Oct 2 '06 #29

P: n/a

Christopher Layne wrote:
FireHead wrote:
In terms of portablilty anybody should be able these codes.

Not when it's a minotaur maze.
then code that I have currently will still work for any platform.

I don't know about that one, but I'm not going to argue it.
One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.

Well, the equiv is VirtualAlloc() on windows. Anyways, away from mmap()
and equivalents - it looks like your primary purpose is doing a bunch of
length/size management and appropriately returning a line without initial
buffer size having to be known - yet you force it all with:

return readLPreLine(pSource,content,512); /* default UNIX length */

Why bother with all the other crap if you're maxing out at 512??

size_t blah(char *d, size_t sz, FILE *f)
{
char buf[512];

if (fgets(buf, sizeof(buf), f) == NULL) {
/*
* this requires you to check " == (size_t)-1"
* the alternative is 0, which may not be accurate for your case
* or ssize_t (which is not ANSI, but POSIX) or just an int.
*/
return -1;
}

return (strlen(buf) - 1);
}

Or perhaps I'm misunderstanding your purpose - as it was fairly hard to
understand from looking at it.

Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.

The point of mmap() is to providely memory mapped files and to not have to
play around with copies of things unless you need the copies.
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.

There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).

I had to give 512 as the default size; but if/when there an need for a
bigger memory then function will exactly handle that.
A example is reading TCP raw streams which have more than 512 bytes in
stream length. By using this function, the function automatically the
adjusts the size if need more than 512 bytes.
Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
Since I am a boolean gates which have a size of 1 bit and in terms of
type declaration short type had fitted the target.

Could you explain how does integer more efficient? I would be
interested about this.

There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).
When you are about use a function your proverb is correct.
And when you look at the driver module you will see that the KISS
methology is implemented.
>From my POV driver module looked straight simple to me.
By making into a challenging environment I will create a jealousy and
moral aggrevation between individual programmer that are hovering about.

Oct 2 '06 #30

P: n/a

Christopher Layne wrote:
FireHead wrote:
In terms of portablilty anybody should be able these codes.

Not when it's a minotaur maze.
then code that I have currently will still work for any platform.

I don't know about that one, but I'm not going to argue it.
One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.

Well, the equiv is VirtualAlloc() on windows. Anyways, away from mmap()
and equivalents - it looks like your primary purpose is doing a bunch of
length/size management and appropriately returning a line without initial
buffer size having to be known - yet you force it all with:

return readLPreLine(pSource,content,512); /* default UNIX length */

Why bother with all the other crap if you're maxing out at 512??

size_t blah(char *d, size_t sz, FILE *f)
{
char buf[512];

if (fgets(buf, sizeof(buf), f) == NULL) {
/*
* this requires you to check " == (size_t)-1"
* the alternative is 0, which may not be accurate for your case
* or ssize_t (which is not ANSI, but POSIX) or just an int.
*/
return -1;
}

return (strlen(buf) - 1);
}

Or perhaps I'm misunderstanding your purpose - as it was fairly hard to
understand from looking at it.

Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.

The point of mmap() is to providely memory mapped files and to not have to
play around with copies of things unless you need the copies.
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.

There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).

I had to give 512 as the default size; but if/when there an need for a
bigger memory then function will exactly handle that.
A example is reading TCP raw streams which have more than 512 bytes in
stream length. By using this function, the function automatically the
adjusts the size if need more than 512 bytes.
Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
Since I am a boolean gates which have a size of 1 bit and in terms of
type declaration short type had fitted the target.

Could you explain how does integer is more efficient? I would be
interested about this.
There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).
When you are about use a function your proverb is correct.
And when you look at the driver module you will see that the KISS
methology is implemented.
>From my POV driver module looked straight simple to me.
By making into a challenging environment I will create a jealousy and
moral aggrevation between individual programmer that are hovering about.

Oct 2 '06 #31

P: n/a

Christopher Layne wrote:
FireHead wrote:
In terms of portablilty anybody should be able these codes.

Not when it's a minotaur maze.
then code that I have currently will still work for any platform.

I don't know about that one, but I'm not going to argue it.
One this is definitely you are right about is that I have rewrite the
source code.
One more pointer is that if I use mmap it will solve my problem that is
to avoid calling the function free() in unix/Linux and other BSD
variants. But for windows it will a portability issue in the case of
using mmap function.

Well, the equiv is VirtualAlloc() on windows. Anyways, away from mmap()
and equivalents - it looks like your primary purpose is doing a bunch of
length/size management and appropriately returning a line without initial
buffer size having to be known - yet you force it all with:

return readLPreLine(pSource,content,512); /* default UNIX length */

Why bother with all the other crap if you're maxing out at 512??

size_t blah(char *d, size_t sz, FILE *f)
{
char buf[512];

if (fgets(buf, sizeof(buf), f) == NULL) {
/*
* this requires you to check " == (size_t)-1"
* the alternative is 0, which may not be accurate for your case
* or ssize_t (which is not ANSI, but POSIX) or just an int.
*/
return -1;
}

return (strlen(buf) - 1);
}

Or perhaps I'm misunderstanding your purpose - as it was fairly hard to
understand from looking at it.

Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
I was trying replicate sort of using my function called get_Copy().
By using the function get_Copy I should be elminate the usage of mmap
somehow.

The point of mmap() is to providely memory mapped files and to not have to
play around with copies of things unless you need the copies.
For the UNIX thinkers the proverb goes in the following way:
< No news is good news>.

There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).

I had to give 512 as the default size; but if/when there an need for a
bigger memory then function will exactly handle that.
A example is reading TCP raw streams which have more than 512 bytes in
stream length. By using this function, the function automatically the
adjusts the size if need more than 512 bytes.
Also, what's up with the short return types? It smells of pre-optimization of
some sort, and if that's the case - it will most likely be more efficient to
just return an int or size_t.
Since I am a boolean gates which have a size of 1 bit and in terms of
type declaration short type had fitted the target.
By using 32765 data limit for me it was too much and not needed.
Short type as you is only 0 - 255.
Why use type integer?
Could you explain how does integer is more efficient? I would be
interested about this.
There's a larger more important proverb: Keep It Simple (unless you have a
really good reason not to).
When you are about use a function your proverb is correct.
And when you look at the driver module you will see that the KISS
methology is implemented.
>From my POV driver module looked straight simple to me.
Oct 2 '06 #32

P: n/a
On 2 Oct 2006 00:14:11 -0700, "FireHead"
<sa************@htech.health.nsw.gov.auwrote:
>Hello All,

My original topic should have been " using/replace fgets".

I think i have finally solved and used fgets in my program.
But I see somewhere bug/memory leak I just am not able pin the memory
leak.
Could anybody assist me in this issue please.
Your code does not compile cleanly. It is riddled with constraint
violations, undefined behavior, and obvious logical errors. In the
spirit of learning to walk before running, I suggest you start with
simpler projects.
>
The this the code that I have managed to get it working.
If it doesn't compile cleanly, working is a forlorn hope.
>//-------------------------------------------------------------------------------------------------------------------------------------------------//
/*
Will BE MULTITHREADED
open a original file (source file)
Look for the existing custom folder in the HOME directory
If the HOME directory does not exist
Then see if the specs exists in the /usr/local/share (Default)
If the /usr/local/share does not exist then create a template
create a temp
*/

#include <cliargs.h>
A non-standard header. We need to see it if we are going to help.
>short readPreLine(FILE* pSource,char **content);
short readPostLine(FILE* pSource,char **content);
short readLPostLine(FILE *pSource,char** content,int default_length);
short readLPreLine(FILE *pSource,char** content,int default_length);
char* get_Copy(char* pStr);

char* get_Copy(char* pStr){
u_int8_t *temp =0;
u_int8_t *final =0;
u_int8_t byte = 0;
u_int8_t dummy = 0;
temp = pStr;
Didn't your compiler complain about incompatible pointer types here?
Even if u_int8_t is a typedef for unsigned char, pStr is not a pointer
to this type.
>int pos = 0;
final = &dummy;
/*initilize the contents with new address*/
do{
byte = *temp;printf("%c",byte);
final++;
At each iteration of this loop, the pointer final is incremented to
point some number of bytes further beyond the end of dummy.
> temp++;
}while(byte!='\0');
*final = '\0';
Since final no longer points to dummy or to any memory you have the
right to write to, this invokes undefined behavior. Since final
points to an integer type, why are you using character notation?
>
temp = "";
You went to some trouble in the preceding while loop to have temp
point one beyond the '\0' that terminates pStr. You have now lost
that address and replaced it with the address of a string literal.
>temp = pStr;
You obviously don't care about the string literal either. temp now
points to the start of the input string.
>/*clean up everything*/

char *results = "";
Those of us with C89 compilers can't help you if you define objects
after executable statements. This is a C99 feature.
>results = strcpy( final,temp);
This also invokes undefined behavior. Even if you hadn't altered
final in the while loop, it would still not point to an area large
enough to receive a string of length greater than 0.
>
return results;
}
/*
short get_Stream(FILE* pSource,char* result){
size_t buflen = 0;
char offset= 0;
int ret=EXIT_SUCCESS;
fpos_t* pCurPos=0 ; //current file position
fpos_t* pOldPos=0 ; //old file position
char *finally = "";
char *buffer = 0;
//get the starting File pointer position
fgetpos(pSource,&pOldPos);
Didn't your compiler complain here. The second argument to fgetpos
must have type fpos_t*. Your code has type fpos_t**.
//find the newline = 0x13
do{offset = 0; offset=fgetc(pSource);
What is the purpose of the first statement? offset is changed
immediately. offset needs to be an int (see below).
} while(offset!=0x0A && offset!=0x0D && offset!=EOF && offset!=NULL &&
offset!=0xFF);
offset is a char. NULL could be defined as (void*)0. If so, this is
another constraint violation. As your code stands now, there is no
guarantee that EOF can be represented in a char.
>
//get the Current File position
fgetpos (pSource,&pCurPos);
printf("%u",pCurPos);
More undefined behavior. %u is for unsigned int. Your argument has
type fpos_t*.
//Total Buffer Length
buflen = (size_t)pCurPos - (size_t)pOldPos;
if(( offset == 0xFF || offset == EOF || offset==NULL) && (buflen ==
EXIT_FAILURE || buflen == EXIT_SUCCESS))
buflen is a size_t. There is no guarantee that either EXIT_FAILURE or
EXIT_SUCCESS can be represented as a size_t. Furthermore, you seem to
think these values have some significance in relation to length of a
buffer. They don't; though it might appear that way on your system.
ret= EXIT_FAILURE;
else{
//Reset Everything
fsetpos (pSource,&pOldPos);
Another constraint violation.
//allocate memory for the new address register
buffer = (char *)malloc(buflen);
Don't cast the return from malloc. It can't help and could cause the
compiler to suppress a diagnostic you would really want to see.
//read file buffer using fgets
fgets(buffer,buflen,pSource);
//copy the string to a automatic variable register
//finally = get_Copy(buffer);
printf("\nfeof = %d\n",strlen(buffer));
More undefined behavior. strlen returns a size_t which will be
unsigned but not necessarily int. %d requires a signed int.
>
//free the contents
free(buffer);

ret=EXIT_SUCCESS;
}//ELSE

buffer=0;
pCurPos = 0;
pOldPos = 0;
offset = 0;
Why are you bothering to assign to automatic variables that will
disappear after the next statement.
return ret;
}*/
Sorry, there didn't seem to be any point to going beyond these two
functions.
Remove del for email
Oct 2 '06 #33

This discussion thread is closed

Replies have been disabled for this discussion.