在我大学的基础 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/