gpt4 book ai didi

c++ - unistd read() 不起作用

转载 作者:行者123 更新时间:2023-11-30 03:29:36 29 4
gpt4 key购买 nike

我正在尝试使用 unistd 库写入/读取文本文件。稍后我会把它部署到/dev路径下的一个文件中。我正在尝试使用 std::vector 类型而不是 char buffer[]。所以我写了两个实现,一个使用 vector ,另一个使用字符缓冲区。两者都在文件中写得很好,但都不能读取文件。

这是我的测试代码:

使用字符缓冲区

void tests_using_buffer_of_char(const std::string &path)
{
int file_descriptor_char;
char buffer[8] ={0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
std::cout << sizeof(buffer) << std::endl;

for(auto i = 0; i < sizeof(buffer); i++)
std::cout << buffer[i] << std::endl;

file_descriptor_char = open(path.c_str(), O_RDWR);
if(file_descriptor_char != -1)
std::cout << "open with success " << path << std::endl;

std::size_t size = strlen(buffer);
ssize_t write_bytes = write(file_descriptor_char, buffer, size);
std::cout << size << " <-- size of buffer " << write_bytes << " <-- size of writed bytes" << std::endl;

memset(&buffer[0], 0, sizeof(buffer));

ssize_t read_bytes = read(file_descriptor_char, &buffer, size);
std::cout << size << " <-- size of buffer " << read_bytes << " <-- size of readed bytes" << std::endl;

for(auto i = 0; i < sizeof(buffer); i++)
std::cout << buffer[i] << std::endl;

if(close(file_descriptor_char) != -1)
std::cout << "close with success "<< path << std::endl;
}

使用 vector 缓冲区

void tests_using_buffer_of_vector(const std::string &path)
{
int file_descriptor_vector;
std::vector<char> buffer = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
std::cout << buffer.size() << std::endl;

for(auto i : buffer)
std::cout << i << std::endl;

file_descriptor_vector = open(path.c_str(), O_RDWR);
if(file_descriptor_vector != -1)
std::cout << "open whit success " << path << std::endl;

ssize_t write_bytes = write(file_descriptor_vector, buffer.data(), buffer.size());
std::cout << buffer.size() << " <-- size of buffer " << write_bytes << " <-- size of writed bytes" << std::endl;

buffer.clear();

ssize_t read_bytes = read(file_descriptor_vector, buffer.data(), write_bytes);
std::cout << buffer.size() << " <-- size of buffer " << read_bytes << " <-- size of readed bytes" << std::endl;

for(auto i : buffer)
std::cout << i << std::endl;

if(close(file_descriptor_vector) != -1)
std::cout << "close with success " << path << std::endl;

}

谢谢大家!

最佳答案

1] 只需使用fclose 并重新打开文件。

2] fseek(fp, 0, SEEK_SET);

3] 倒带(fp);

您使用文件指针指向文件末尾。

关于c++ - unistd read() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45574727/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com