You are attempting to use a string-funciton on a buffer that is not nul-terminated resulting in Undefined Behavior. Specifically:
char buf[100];
char c;
while ((c = fgetc(fp)) != EOF)
strncat(buf, c, 1);
On your first call to strncat
, buf
in uninitialized resulting in Undefined Behavior due to strncat()
replacing the existing nul-terminating character (which doesn't exist) with the new text to be appended. You can initialize buf
all zero with:
char buf[100] = "";
That will fix the immediate Undefined Behavior but will not prevent you later reading beyond the bounds of buf
when you read past the 99th character.
Instead, declare a counter and initialize the counter zero, and use that to limit the number of characters read into your buf
, as in the comment:
size_t n = 0;
while (n + 1 < 100 && (c = fgetc(fp)) != EOF) {
buf[n++] = c;
}
buf[n] = 0; /* don't forget to nul-terminate buf */
You can put it altogether and avoid using Magic-Numbers (100
) as follows:
#include <stdio.h>
#define MAXC 100 /* if you need a constant, #define one (or more) */
int main (int argc, char* argv[]) {
if (argc < 2) { /* validate one argument given for filename */
fputs ("error: too few arguments.
", stderr);
return 1;
}
char buf[MAXC] = "", c;
size_t n = 0;
FILE* fp = fopen (argv[1], "r");
if (fp == NULL) { /* validate file open for reading */
perror ("fopen-argv[1]"); /* on failure, perror() tells why */
return 1;
}
/* while buf not full (saving 1-char for ), read char */
while (n + 1 < MAXC && (c = fgetc(fp)) != EOF)
buf[n++] = c; /* assign char to next element in buf */
buf[n] = 0; /* nul-terminate buf */
puts (buf); /* output result */
fclose(fp);
}
(note: the comparison with n + 1
ensures one-element in buf
remains for the nul-terminating character)
Example Use/Output
$ ./bin/read100chars read100chars.c
#include <stdio.h>
#define MAXC 100 /* if you need a constant, #define one (or more) */
in
(note: the first 'n'
in int main (...
is the 99th character in the file)
Look thing over and let me know if you need further help. (note with VS you will likely need to pass /w4996
to disable the "CRT Secure...."
warning.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…