2

在我大学的基础 Linux 编程课程中,我们使用 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

这是程序,供您参考。谢谢!:)

4

2 回答 2

0

第一个的问题

statusOfFunction = read(fileDescriptor, reading.c_str(), 10);

就是c_str声明返回一个const指针。否则,这是接近正确方法的方法。

首先,您需要创建一个至少包含 10 个字符的字符串:

std::string temp_string(10, ' ');  // Creates a string contains 10 spaces

然后你需要传递一个非常量指针,你可以通过使用地址操作符&和字符串数组索引操作符来获得[]

statusOfFunction = read(fileDescriptor, &temp_string[0], temp_string.length());

最后你将它分配给实际的字符串:

reading = std::string(temp_string, 0, statusOfFunction);

当然,您应该检查statusOfFunction它不是错误(当它时-1)或文件结尾(当它时0)。


您尝试阅读的所有其他方法都是非常错误的。

于 2014-09-23T08:51:17.010 回答
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);
于 2014-09-23T08:51:53.543 回答