正如其他答案指出的那样,您正在向printf传递一个可能不是NULL终止的字符串。您也没有验证正在读取的文件是否大于100个字节。最后一点,在fread()
您换了size_t size
和size_t niters
参数。
这是你的程序的修改版本,修正了上述问题(和清理间隔位):
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
FILE *fr;
char c[1];
struct stat sb;
// obtains information about the file
if (stat(argv[1], &sb) == -1)
{
perror("stat()");
return(1);
};
// verifies the file is over 100 bytes in size
if (sb.st_size < 101)
{
fprintf(stderr, "%s: file is less than 100 bytes\n", argv[1]);
return(1);
};
// opens the file, or prints the error and exists
if (!(fr = fopen (argv[1], "r")))
{
perror("fopen():");
return(1);
};
fseek(fr, 100, SEEK_CUR);
while (fread(c, sizeof(c), 1, fr) > 0)
printf("%c", c[0]);
fclose(fr);
return(0);
}
您也可以通过改变char c[1];
的东西线提高阅读该文件的效率char c[1024];
和更新,同时声明:
while (fread(c, sizeof(char), 1023, fr) > 0)
{
c[1023] = '\0';
printf("%s", c);
};
请注意,一次读取多于1个字节,然后使用printf假定输入文件是不含NULL字符的文本文件。 – 2012-01-17 00:22:45