使用系统调用(打开、读取、写入)显示文件内容

Using systems calls (open, read, write) to display file content

我正在尝试执行一个名为 displaycontent 的命令,该命令将文本文件名作为参数并显示其内容。我将在 Linux 中使用 open()read()write()close() 系统调用来执行此操作。它应该有点像用于显示文件内容的 UNIX cat 命令。

这是我目前的情况:

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

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

    errno = 0;
    fd = open(argv[1], O_RDONLY);


    if(fd < 0)
    {
        printf("File could not be opened.\n");
        perror("open");
        return 1;
    }
    else 
    {

        read(fd, content, sizeof(content)-1);
        write(1, content, sizeof(content)-1);
    }

return 0;
}

我有一个名为 hello2.txt 的文件,其中包含文本:hellooooooooooooooo

当我执行 ./displaycontent hello2.txt 时,我得到:

user@user-VirtualBox:~/Desktop/Csc332/csc332lab$ ./displaycontent hello2.txt
hellooooooooooooooo
����>k���[`�s�b��user@user-VirtualBox:~/Desktop/Csc332/csc332lab$ 

文件内容后面有奇怪的符号和东西。我不确定出了什么问题,如有任何帮助,我们将不胜感激。谢谢。

fd没有初始化,所以content的大小没有确定。

无论如何,你不应该为此使用 fd。如果这只是一个练习,您可以使用一个大的固定数字。否则,您需要获取文件大小并使用它。

要获取文件长度,您可以按照这个例子:

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

int main()
{
    int fd = open( "testfile.txt", O_RDONLY );
    if ( fd < 0 )
        return 1;

    off_t fileLength = lseek( fd, 0, SEEK_END );  // goes to end of file
    if ( fileLength < 0 )
        return 1;

    //  Use lseek() again (with SEEK_SET) to go to beginning for read() call to follow.
    close( fd );
    return 0;
}

(今天没有编译,凭记忆,如果有错别字,应该是轻微的)

use bytes = read (fd,content,sizeof(content)-1); to capture the number of bytes read. Then use bytes in write(1,content,bytes); to only write the bytes that were read. – user3121023