未在终端中打印的文件内容

时间:2015-01-16 08:19:42

标签: c file fwrite

您好我正在尝试从文件中读取并在终端上打印。但fwrite()不会打印任何内容。谁能请帮忙!我无法在终端上看到文件的输出。经过调试后,我可以看到程序没有进入fwrite()之前使用的while循环。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#define BUF_SIZE 128

int main(int argc, char* argv[]) 
{
    int BATT_fd, ret_write, ret_read, i;
    char buffer[BUF_SIZE];      

    if(argc != 2)
    {
        printf ("\nUsage: cp file1 file2\n");
        return 1;
    }

    BATT_fd = open (argv [1], O_RDWR | O_CREAT, S_IRWXU);

    if (BATT_fd == -1) 
    {
        perror ("open");
        return 2;
    }

 printf("\n file opened successfully with file desc %d\n", BATT_fd);
 printf("enter data into file\n");
 scanf("%[^\n]", buffer);

     if((ret_write = write (BATT_fd, &buffer, BUF_SIZE)) == 0)
     { 
         printf("nothing is write");    
     }
     else if((ret_write = write (BATT_fd, &buffer, BUF_SIZE)) == -1)
     { 
         printf("write error"); 
     }
     else
     {
         printf("wrote %d characters to file\n", ret_write);
         printf("address writeen is %x\n", buffer[i]);
     }

     if((ret_read = read(BATT_fd, &buffer, BUF_SIZE)) > 0)
     { 
        perror("read"); 
        return 4;
     }
     else
     {
        while((ret_read = read (BATT_fd, &buffer, BUF_SIZE)) > 0)
        {
            fwrite(buffer, 1, ret_read, stdout);
        }
     }

 close (BATT_fd);

 return 0;
}

输出:

enter image description here

1 个答案:

答案 0 :(得分:3)

在从文件中读取数据之前,需要将文件中的当前位置移动到开头。那是因为你的写操作已将当前位置移动到文件末尾,因此没有任何内容可供阅读;)。

见fseek

修改

lseek在你的情况下会更好(见评论)