2012-10-05 33 views
1

下面是我的代碼在追加方式寫入文件:如何使用fcntl.h

#include <iostream> 
#include <fcntl.h> 
#include <unistd.h> 
using namespace std; 

int main() 
{ 

int filedesc = open("testfile.txt", O_RDWR | (O_APPEND |O_CREAT) ,S_IRWXO); 

    if (filedesc < 0) { 
    cout<<"unable to open file"; 
     return -1; 
    } 

    if (write(filedesc, "This will be output to testfile.txt", 36) != -1) { 
     cout<<"writing"; 
     close(filedesc); 
    } 

    return 0; 
return 0; 

} 

如果我上面第二次O/P是「無法打開文件」相同的運行。 我做錯了什麼?

+0

使用'perror'函數將提供有關該錯誤的原因的其他信息:http://www.cplusplus.com/reference/clibrary/cstdio/perror/ –

+1

混合C和C++是有時會受到批評,即c-open和C++ - cout的混合。考慮獨家使用。 –

+2

@RudolfMühlbauer'open'不是C,它是POSIX。除非你有一個C++ POSIX包裝來暗示我沒有看到他應該怎麼做(除非你希望他使用C++ std而不是POSIX)。 – CrazyCasta

回答