gpt4 book ai didi

c - 如何从 read() 中获取字符

转载 作者:行者123 更新时间:2023-11-30 17:46:22 25 4
gpt4 key购买 nike

我正在尝试仅使用 open()read()write() 复制文件以向后打印它。但是我想知道是否有一种方法可以从读取中获取字符指针,该指针返回读取的字节数。如果是这样,我该怎么做,我已经尝试过一次,但最终出现了错误

error: invalid type argument of ‘unary *’ (have ‘ssize_t’)

这是我正在使用的代码片段

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main (int argc, char *argv[])
{
if(argc != 3)/*argc should be 2 for correct execution*/
{
printf("usage: %s filename",argv[0]);
}
else
{
int file1 = open(argv[1], O_RDWR);
if(file1 == -1){
printf("\nfailed to open file.");
return 1;
}
int reversefile = open(argv[2], O_WRONLY, O_CREAT);
int size =(int)lseek(file1, 0, SEEK_END)+1;
char file2[size];
int count=size;
int i = 0;

while(read(file1, &file2[count], 1) != 0)
{
*file2[i]=*read(file1, file[count], 1);
write(reversefile, file2[i], size+1);
count--;
i++;
lseek(reversefile, i, SEEK_SET);
}
}

最佳答案

read 返回一个 size_t 值,指示成功读取了多少字节,它不返回指针。

为了您的目的,您首先需要调用 read

read(file1, &file2[count], 1)

然后您可以通过

访问从文件中读取的值
file2[i] = file[count];

而且我认为您不需要调用 read 两次。

此外,如果您只想要一个字符,那么使用 getc 会更好。

char c;
while((c=getc(file1)) != EOF){
// use c
}

关于c - 如何从 read() 中获取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19328744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com