Replacing fgets

F

FireHead

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.
 
C

CBFalconer

FireHead said:
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/>
 
F

FireHead

Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
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.
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.
 
R

Richard Heathfield

FireHead said:
Hello CBFalconer

I am looking at this code more of C code rather than a C++ code.
I have tried this code.
and I have found a few memory leaks.

<snorfle>

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

Richard Tobin

[/QUOTE]
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
 
R

Richard Heathfield

Richard Tobin said:
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?[/QUOTE]

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.
 
C

CBFalconer

FireHead said:
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.
 
R

Richard Heathfield

CBFalconer said:
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!"
 
K

Keith Thompson

FireHead said:
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.

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.
 
B

Bill Reid

CBFalconer said:
This is a C++ operation.
How perceptive...
... snip ...

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,NEXTLINE))!=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...
 
C

CBFalconer

Bill said:
.... snip ...


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.
 
B

Bill Reid

CBFalconer said:
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,NEXTLINE,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,NEXTLINE,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,GETLINE);
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_line,POSITION);

/* now read and print the rest of the file */
while((get_text_line(file_buffer,test_line_buf,NEXTLINE,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,GETLINE);
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,GETLINE);
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...
 
F

FireHead

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



Bill said:
CBFalconer said:
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,NEXTLINE,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,NEXTLINE,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,GETLINE);
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_line,POSITION);

/* now read and print the rest of the file */
while((get_text_line(file_buffer,test_line_buf,NEXTLINE,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,GETLINE);
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,GETLINE);
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...
 
P

pete

FireHead said:
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 */
 
F

FireHead

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.
 
K

Keith Thompson

FireHead said:
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.
 
F

FireHead

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 said:
FireHead said:
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.
 
K

Keith Thompson

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

FireHead said:
Keith said:
FireHead said:
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/>
 
F

FireHead

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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top