简体   繁体   中英

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. 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() .

#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

EDIT:

lseek would be better in your case (see comments)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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