终端不打印文件内容
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 对你来说会更好(见评论)
您好,我正在尝试读取文件并在终端上打印它。但是 fwrite()
不打印任何东西。谁能帮忙!我在终端上看不到文件的输出。调试后我能看到的是程序没有进入 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;
}
输出:
在从文件中读取数据之前,您需要将文件中的当前位置移动到开头。那是因为你的写操作已经将当前位置移动到文件末尾,所以没有任何东西可以读了;)。
参见 fseek
编辑:
lseek 对你来说会更好(见评论)