gpt4 book ai didi

c - 使用系统调用读写

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:05 25 4
gpt4 key购买 nike

我必须使用读取文件并使用系统调用将信息写入另一个文件。我已经打开文件阅读如下
filedesc = open(argv[1],O_RDONLY);//哪个工作正常打开一个文件写如下: fdw=creat(strcat(store,argv[1]),PERMS)//PERMS 0666使用 lseek 到达文件 filedesc 之一(反转和打印)

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

int main(int argc, char *argv [ ])
{

int filedesc,n,i,fdw,pos;
char c;
const char * prefix = "reserve_";
int needed = strlen( argv[ 1 ] ) + strlen( prefix ) + 1;
char store[ needed ];
strcpy( store, prefix );

if(argc != 2)
{
printf(" usage : %s filename ", argv[0]);
}

//strcat( store, argv[ 1 ] );
//printf( "%s\n", store );


filedesc = open(argv[1],O_RDONLY);
if(filedesc <1 )
{ printf("Unable to open file\n");
exit(1); }


if((fdw=creat(strcat(store,argv[1]),PERMS))==-1)
printf("Unable to create file,please use perror to find details\n");
else printf("File created\n");



if((pos=lseek(filedesc,0,SEEK_END))==0)
{
printf("Empty file\n");
exit(-1);
}
i=pos-1;
//printf("%d",i);

while(i!=0)
{
pos=lseek(filedesc,i-1,SEEK_SET);
read(filedesc,&c,1);
if( write(fdw,&c,1)!=1) //information is not being written to the file
printf("Error\n"); //pointed by fdw rather getting printed on the
//screen
i--;
}

close(filedesc);
close(fdw);



}

问题:如果我在没有第一个参数的情况下运行它,它会给出段错误而不是用法。请帮忙

最佳答案

您的 if 行是错误的。它实际上会将比较的结果存储fdw中,而不是存储creat(2)的结果。

if(fdw=creat(strcat(store,argv[1]),PERMS)==-1) /* Wrong. */

尝试:

if((fdw = creat(strcat(store, argv[1]), PERMS)) == -1)
^ ^

编辑

您还应该检查 read 的结果:

if (read(filedesc, &c, 1) <= 0)
break;

关于c - 使用系统调用读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7130168/

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