簡體   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