A
arnuld
I wrote this program which reads a file and prints it onto stdout
using fgets().
PROBLEM: fgets() reads line by line into an array. Lets say, in input
file, first line is longer than 2nd line. Then after reading first
line into array all characters read must be present in the array when
it reads 2nd line e.g.
1st line: usenet
2nd line: clc
after reading first line contents of array: usenet
(array is not memset()ed)
after reading second line contents of array: clc (why not clcnet)
which means /use/ of /usenet/ was not replaced by /clc/ but contents
of array were replaced/cleared. (slashes are used for readability
here, emphasizing single words).
QUESTION: My question is I did not clear array contents after one call
to fgets() then who did ? fgets() ?
#include <stdio.h>
#include <stdlib.h>
enum { FGETS_READ_MAX = 256 };
void print_file(FILE* p);
int main(void)
{
const char* filename = "dp.conf";
FILE* filep;
filep = fopen(filename, "r");
if(NULL == filep)
{
fprintf(stderr,"IN: %s @%d: ERROR opening file\n", __FILE__,
__LINE__);
return EXIT_FAILURE;
}
print_file(filep);
if(fclose(filep))
{
printf("IN: %s @%d: ERROR closing file\n", __FILE__, __LINE__);
}
return 0;
}
void print_file(FILE* p)
{
char arrc[FGETS_READ_MAX + 2] = {0};
while(fgets(arrc, FGETS_READ_MAX, p))
{
printf("\t::%s", arrc);
}
if(feof(p))
{
printf("Successful EoF EXIT \n");
}
else if(ferror(p))
{
printf("IN: %s @%d: ERROR reading file\n", __FILE__, __LINE__);
}
else
{
printf("OOPS! .. some other kind of issue ??\n");
}
}
using fgets().
PROBLEM: fgets() reads line by line into an array. Lets say, in input
file, first line is longer than 2nd line. Then after reading first
line into array all characters read must be present in the array when
it reads 2nd line e.g.
1st line: usenet
2nd line: clc
after reading first line contents of array: usenet
(array is not memset()ed)
after reading second line contents of array: clc (why not clcnet)
which means /use/ of /usenet/ was not replaced by /clc/ but contents
of array were replaced/cleared. (slashes are used for readability
here, emphasizing single words).
QUESTION: My question is I did not clear array contents after one call
to fgets() then who did ? fgets() ?
#include <stdio.h>
#include <stdlib.h>
enum { FGETS_READ_MAX = 256 };
void print_file(FILE* p);
int main(void)
{
const char* filename = "dp.conf";
FILE* filep;
filep = fopen(filename, "r");
if(NULL == filep)
{
fprintf(stderr,"IN: %s @%d: ERROR opening file\n", __FILE__,
__LINE__);
return EXIT_FAILURE;
}
print_file(filep);
if(fclose(filep))
{
printf("IN: %s @%d: ERROR closing file\n", __FILE__, __LINE__);
}
return 0;
}
void print_file(FILE* p)
{
char arrc[FGETS_READ_MAX + 2] = {0};
while(fgets(arrc, FGETS_READ_MAX, p))
{
printf("\t::%s", arrc);
}
if(feof(p))
{
printf("Successful EoF EXIT \n");
}
else if(ferror(p))
{
printf("IN: %s @%d: ERROR reading file\n", __FILE__, __LINE__);
}
else
{
printf("OOPS! .. some other kind of issue ??\n");
}
}