pag*_*ge4 1 c system-calls cat
我正在尝试实现一个名为 displaycontent 的命令,该命令将文本文件名作为参数并显示其内容。我将在 Linux 中使用open()、read()、write()和close()系统调用来执行此操作。它应该有点像cat用于显示文件内容的 UNIX命令。
这是我到目前为止所拥有的:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个名为 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$
Run Code Online (Sandbox Code Playgroud)
文件内容后面有奇怪的符号和东西。我不确定出了什么问题,任何帮助将不胜感激。谢谢你。
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;
}
Run Code Online (Sandbox Code Playgroud)
(我今天没有编译,只是凭记忆。如果有错别字,应该是轻微的)