简体   繁体   English

文件内容未在终端中打印

[英]Contents of file not being printed in terminal

Hi I am trying to read from a file and print it on terminal. 嗨,我试图从文件中读取并在终端上打印。 But fwrite() does not print anything. 但是fwrite()不会打印任何内容。 Can anyone please help! 谁能帮忙! I cannot see the output from the file on the terminal. 我在终端上看不到文件的输出。 After debugging all I can see is program is not entering into while loop used before 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;
}

output: 输出:

在此处输入图片说明

Before reading data from file, you need to move current position in file to the begining. 从文件读取数据之前,您需要将文件中的当前位置移动到开头。 That's because your write operations have moved current position to the end of file, so there is nothing left for reading ;). 那是因为您的写操作已经将当前位置移到了文件的末尾,因此没有剩余要读取的内容;)。

see fseek 见fseek

EDIT: 编辑:

lseek would be better in your case (see comments) lseek在您的情况下会更好(请参阅评论)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM