unistd read()不起作用

时间:2017-08-08 17:37:08

标签: c++ c++11 vector unistd.h

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

这是我的测试代码:

使用char缓冲区

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;
}

使用矢量缓冲区

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;

}

谢谢大家!

2 个答案:

答案 0 :(得分:1)

在将文件描述符用于写入之后,必须将文件描述符重置为文件的开头,然后再尝试将其重新用于读取。你可以关闭文件并重新打开它,或者你可以寻找开头。

lseek(file_descriptor_vector, SEEK_SET, 0);

在阅读之前不要清除你的矢量。 clear方法将基本上释放与向量关联的内存。

答案 1 :(得分:1)

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

2] fseek(fp, 0, SEEK_SET);

3] rewind(fp);

您使用file pointer指向文件的末尾。