繁体   English   中英

文件内容未在终端中打印

[英]Contents of file not being printed in terminal

嗨,我试图从文件中读取并在终端上打印。 但是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;
}

输出:

在此处输入图片说明

从文件读取数据之前,您需要将文件中的当前位置移动到开头。 那是因为您的写操作已经将当前位置移到了文件的末尾,因此没有剩余要读取的内容;)。

见fseek

编辑:

lseek在您的情况下会更好(请参阅评论)

暂无
暂无

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

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