解决linux下写一个文件之后立马读,读出乱码或者空白的问题



1、利用read函数立即读的话,不能读出写入的内容。

问题分析,因为写完之后指针还在后面,即偏移量不为0,所以读取的时候开始位置刚好是刚才写的末尾,所以不可能读取到内容。

解决方法:添加一句将偏移量设置为0的代码:lseek(fd,0,SEEK_SET);  此外为了保险起见,还可以在打开文件的时候天剑上O_SYNC标志,以便同步到磁盘。

    fd=open("test.txt",O_RDWR|O_SYNC);

2、利用lseek增加偏移之后,在写入,出现空洞现象,空洞会被“\0”填充,此时用cout<

解决方法:cout遇到“\0”的时候默认到了字符串尾部。

#include
#include 
#include
#include


using namespace std;
#define MAX_SIZE 512


int main(){
    int fd,fdwr,fdwr2,fdrea1,fdrea2;
    off_t fd2;
    char buf1[]="my name is Tony.";
    char buf2[]="what is your name?";
    char buf[MAX_SIZE];
    fd=open("test.txt",O_RDWR);
    if(fd<0)
    {
        cout<<"error\n"<


你可能感兴趣的:(C++)