简体   繁体   English

C-使用系统调用打印文件?

[英]C - print file using system calls?

I'm trying to get aquainted with system calls and C. I'm trying to read a file and write all the contents to the command line. 我试图熟悉系统调用和C。我试图读取文件并将所有内容写入命令行。 I'm trying 我正在努力

int handle = open("./test.txt", O_RDONLY, O_TEXT);
char buf[1];
lseek(handle, 0, SEEK_SET);
while (0 != read(handle, buf, 1)) {
        printf(*buf);
}

This ALMOST works, except that it adds some gibberish characters after each character read from the file. 此ALMOST可以工作,除了在从文件中读取每个字符后添加一些乱码。 For example if the file contains asd asd this writes a:_s:_d:_ :_a:_s:_d to the console. 例如,如果文件包含asd asd这会将a:_s:_d:_ :_a:_s:_d写入控制台。 Any idea why? 知道为什么吗? How can I fix it? 我该如何解决?

Every string has to end with the \\0 (null) character. 每个字符串都必须以\\0 (空)字符结尾。

So try to make your buffer size 2, and just before printf do buf[1] = '\\0'; 因此,尝试将缓冲区的大小设置为2,并在printf之前做buf[1] = '\\0';

In general when you read wcnt (type ssize_t) number of chars you do buf[wcnt] = '\\0'; 通常,当您读取wcnt (type ssize_t)的字符数时,您会buf[wcnt] = '\\0';

Also your printf is not syntaxed correctly safely! 另外你的printf不正确 syntaxed安全! printf("%s", buf);

Edit: As mentioned in other answers and comments (I will not add it since I did not propose it first), you can just print a char in this case. 编辑:如其他答案和评论中所述(由于我没有先提出它,因此我不会添加它),在这种情况下,您可以仅打印一个字符。

You code should produce warnings on most modern compilers. 您的代码应在大多数现代编译器上产生警告。 Because printf() doesn't accept a char . 因为printf()不接受char Since you are reading the file char by char, you can instead use putchar() to print on the stdout. 由于putchar()字符读取文件char,因此可以改用putchar()在标准输出上打印。

while (read(handle, buf, 1) == 1) {
    putchar(buf[0]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM