【发布时间】:2019-11-04 23:34:21
【问题描述】:
我正在尝试仅使用系统调用在 C 中实现 rev linux 调用。我能够实现它,但我的代码也反转了文件的行,因此第 1 行现在是文件中的最后一行。最后一行也不会跳到标准输出上的新行。我不确定它为什么这样做。
这是我的代码:
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#define LINE_BUFFER 1024
int charCount(const char *name1);
int main(int argc, char* argv[]) {
if(argc ==2){
charCount(argv[1]);
}else{
printf("Provide a file\n");
}
return 0;
}
int charCount(const char *name1)
{
char buffer[LINE_BUFFER];
int fd;
int nread;
int i = 0;
if ((fd = open(name1, O_RDONLY)) == -1)
{
perror("Error in opening file");
return (-1);
}
int size = lseek(fd,-1,SEEK_END);
while(size>=0)
{
nread=read(fd,buffer,1);
write(1,buffer,1);
lseek(fd, -2,SEEK_CUR);
size--;
}
close(fd);
return(0);
}
输入
Contents of file 1:
Hello World
Hi World
输出
dlroW iH
dlroW olleH
期望的输出:
dlroW olleH
dlroW iH
【问题讨论】:
-
您的代码没有使用任何系统调用。
-
@Dai read, write, lseek都是linux系统调用。
-
它们是 POSIX 系统函数。我以为你的意思是你会使用
syscall函数。 -
@Dai 好的,我会改写以避免混淆
标签: c linux file operating-system reverse