从 fcntl.h 读取函数中的 C++ 字符串

标签 c++ unix fcntl unistd.h

在我大学的基础 Linux 编程类(class)中,我们使用 fcntl.h 和 unistd.h 使用 C++ 字符串,我得到以下信息:

statusOfFunction = write(fileDescriptor, input.c_str(), input.length());

这条线有效。我创建了一个文件,其中包含输入字符串的内容。但是,为什么这些行中的任何一行都不起作用:

statusOfFunction = read(fileDescriptor, reading.c_str(), 10);
Error: No matching function call to "read"

statusOfFunction = read(fileDescriptor, reading, 10);
Error: No matching function call to "read"

statusOfFunction = read(fileDescriptor, &reading, 10);
No error throws up, but does not get executed

statusOfFunction = read(fileDescriptor, &reading.c_str(), 10);
Error: No matching function call to "read"

https://www.dropbox.com/s/lnw208uo3xurqxf/Basic%20Unix%20Operations%20on%20Text%20Files.cpp?dl=0

这是程序,供您引用。 谢谢你! :)

最佳答案

read 需要一个缓冲区来填充读取的数据。

你的所作所为很危险。

您应该分配一个字符缓冲区,并确保在字符串长度后添加 NULL 字符,因为 read 不会为您做这件事。 c_str 函数公开了字符串类使用的内部缓冲区。它是只读的。

覆盖字符串对象本身肯定会导致以后使用时崩溃。

char buff[11];
size_t bytes_read = read(fd, buff, 10);
buff[bytes_read] = 0; // terminate string
string myString(buff);

关于从 fcntl.h 读取函数中的 C++ 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25990657/

相关文章:

linux - 使用 grep 和 ls -a 命令

python - 有助于文件锁定的实用程序 - 需要专家提示

c++ - 我如何故意触发 fgets() 中的错误?

c - 在终端(C 文件)中运行程序但未运行完成

c++ - 构造函数/析构函数计数不匹配

bash - 在 Unix (bash) 中,如何将通配符附加到变量?

c - 如何强制链接到旧的 libc `fcntl` 而不是 `fcntl64` ?

c - 为什么我不能在设置 F_SEAL_WRITE 后创建只读的共享映射?

c++ - 尝试获取不存在的节点时如何不出现任何错误

c++ - 使用 Info-ZIP 3.0 源代码时出现编译器错误