N
name
When I started testing the algorithms for my wrap program, I threw together
this snippet of code, which works quite well. Except that it (predictably)
segfaults at the end when it tries to go beyond the file. At some point, I
tried to mend that behavior using feof() but without success. The
functionality is not harmed, but this has started to bug me. What am I
missing here? Sometimes being a code duffer is frustrating!! lol!!!
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
FILE *fp;
int len;
char buf[100];
if ((fp = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "can't open fp");
return EXIT_FAILURE;
}
while (((len = strlen(fgets(buf, 80, fp))) != 0)) {
printf(" %i\t", len);
printf("%s", buf);
}
fclose(fp); /* Nah, no error checking here... */
return EXIT_SUCCESS;
}
Thanks for reading.
this snippet of code, which works quite well. Except that it (predictably)
segfaults at the end when it tries to go beyond the file. At some point, I
tried to mend that behavior using feof() but without success. The
functionality is not harmed, but this has started to bug me. What am I
missing here? Sometimes being a code duffer is frustrating!! lol!!!
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
FILE *fp;
int len;
char buf[100];
if ((fp = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "can't open fp");
return EXIT_FAILURE;
}
while (((len = strlen(fgets(buf, 80, fp))) != 0)) {
printf(" %i\t", len);
printf("%s", buf);
}
fclose(fp); /* Nah, no error checking here... */
return EXIT_SUCCESS;
}
Thanks for reading.