无法从文件中读取

时间:2013-12-06 05:38:21

标签: c file-io

我正在撕扯我的头发试图弄清楚为什么这不起作用:

fprintf(stdout, "filename: %s\n", filename); // looks great

// open the requested file
if ((fd = fopen(filename, "r")) == NULL) {
    fprintf(stdout, "Failed to open file: %s\n", filename);
    exit(EXIT_FAILURE);
} else {
    fprintf(stdout, "Successfully opened file: %s\n", filename);
}

do {
    bzero(buffer, BUFFSIZE);  // size 1024 bytes
    bytes_read = fread( &buffer, sizeof(char), BUFFSIZE, fd );
    fprintf(stdout, "buffer contents: %s\n", buffer);
} while (!feof(fd));

fclose(fd);

这是我的输出:

filename: test.txt
Successfully opened file: test.txt
buffer contents: 
buffer contents: 
buffer contents: 009
BEGIN_LINE010This is a test file with exactly 10 lines of readable textEND_LINE010

请注意,它已完全“丢失”文本文件中的前8行。它清楚地打开文件并读取最后一行(加上第9行的尾随3个字符)。这些其他线路在哪里?我完全不知所措。

以下是我想要阅读的整个测试文件:

BEGIN_LINE000This is a test file with exactly 10 lines of readable textEND_LINE000
BEGIN_LINE001This is a test file with exactly 10 lines of readable textEND_LINE001
BEGIN_LINE002This is a test file with exactly 10 lines of readable textEND_LINE002
BEGIN_LINE003This is a test file with exactly 10 lines of readable textEND_LINE003
BEGIN_LINE004This is a test file with exactly 10 lines of readable textEND_LINE004
BEGIN_LINE005This is a test file with exactly 10 lines of readable textEND_LINE005
BEGIN_LINE006This is a test file with exactly 10 lines of readable textEND_LINE006
BEGIN_LINE007This is a test file with exactly 10 lines of readable textEND_LINE007
BEGIN_LINE008This is a test file with exactly 10 lines of readable textEND_LINE008
BEGIN_LINE009This is a test file with exactly 10 lines of readable textEND_LINE009
BEGIN_LINE010This is a test file with exactly 10 lines of readable textEND_LINE010

2 个答案:

答案 0 :(得分:0)

我认为你应该试试这段代码:

   FILE *fp;
   char buff[255];

   char *filename="input.txt";

   fprintf(stdout, "filename: %s\n", filename); // looks great

   if ((fp = fopen(filename, "r")) == NULL) 
   {
        fprintf(stdout, "Failed to open file: %s\n", filename);
        exit(EXIT_FAILURE);
   }   
   else 
   {
        fprintf(stdout, "Successfully opened file: %s\n", filename);
   }   
   while ( !feof(fp ) )
   {
        memset(buff, '\0', sizeof( buff) );
        fgets(buff, 255, (FILE*)fp);
        printf("%s", buff );
   }
   fclose(fp);

答案 1 :(得分:0)

问题是在文本模式下使用fread()混合打开文件通常不是一个好主意

如果以二进制模式“rb”打开文件,则fread应该按预期工作。

另一件事是fread没有\ 0终止它读取的任何内容,也许你试图通过调用“bzero”来终止缓冲区但是如果你读取整个BUFFSIZE字节数,那么缓冲区将没有空间用于尾随\ 0

而是只做一个循环并打印每个字符或ascii值:

do 
{
  bytes_read = fread( &buffer, sizeof(char), BUFFSIZE, fd );
  fprintf(stdout, "buffer contents:");
  for ( i = 0; i < bytes_read; ++i)
  {
    fprintf( stdout, "%2X", buffer[i] );
  }
} 
while (!feof(fd));