Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在不使用stdio.h的情况下读取txt文件的最后n个字符?_C_System Calls - Fatal编程技术网

C 如何在不使用stdio.h的情况下读取txt文件的最后n个字符?

C 如何在不使用stdio.h的情况下读取txt文件的最后n个字符?,c,system-calls,C,System Calls,我试图在不使用stdio.h函数调用的情况下从文本文件中读取最后n个数字。我不确定如何做到这一点,因为如果不使用stdio.h,我无法使用fseek,而且我不熟悉系统调用。任何帮助都将不胜感激 #include <unistd.h> #include <sys/types.h> #include<sys/stat.h> #include <fcntl.h> int main() { int fd; char buf[200]

我试图在不使用stdio.h函数调用的情况下从文本文件中读取最后n个数字。我不确定如何做到这一点,因为如果不使用stdio.h,我无法使用fseek,而且我不熟悉系统调用。任何帮助都将不胜感激


#include <unistd.h>

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

int main() {

    int fd;
    char buf[200];

    fd = open("logfile.txt", O_RDONLY);
    if (fd == -1){
        fprintf(stderr, "Couldn't open the file.\n");
        exit(1); }

    read(fd, buf, 200);

    close(fd);
}

#包括
#包括
#包括
#包括
int main(){
int-fd;
char-buf[200];
fd=打开(“logfile.txt”,仅限ordu);
如果(fd==-1){
fprintf(stderr,“无法打开文件。\n”);
退出(1);}
读取(fd,buf,200);
关闭(fd);
}

您可以使用
lseek
。以下是原型:

off_t lseek(int fd, off_t offset, int whence);
以下是如何将其集成到代码中:

lseek(fd, -200, SEEK_END);
read(fd, buf, 200);
只是为了多样性:

struct stat sb;

int fd = open( filename, O_RDONLY );
fstat( fd, &sb );
pread( fd, buf, 200, sb.st_size - 200 );

请注意,
lseek()
then
read()
不是原子的,因此如果有多个线程正在访问文件描述符,您将有一个争用条件
pread()
是原子的。

您能解释一下为什么不能使用stdio.h吗?看起来您想要使用的是。如果我看到错误消息
无法打开文件。
,我会立即问两个问题。哪个文件?为什么不呢?您的错误消息应该包括这两个详细信息。这可以通过
peror(“logfile.txt”)
轻松实现。第三个问题是“哪个程序?”一些系统也提供了简单的包装,例如
err(EXIT_FAILURE,“logfile.txt”)
@dededecos教我们系统调用是一个家庭作业相关的问题:您运行的是什么操作系统(如果是Linux,是什么发行版)?