繁体   English   中英

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

[英]C++ Strings in Read Function from fcntl.h

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

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

第一个问题

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

c_str被声明为返回const指针。 否则,这接近正确的方法。

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

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

然后,您需要传递一个非常数指针,可以通过使用address-of运算符&和字符串array-indexing运算符[]获得该常数:

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

最后,将其分配给实际的字符串:

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

当然,您应该检查statusOfFunction这样就不会出现错误(当它为-1 )或文件结尾(当它为0 )。


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

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

你在做什么很危险。

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

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

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

暂无
暂无

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

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