I've got a problem with this simple code :
int main(int argc, char const *argv[]) {
int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT);
dup2(fichier, 1);
printf("test");
return 0;
}
I just need to write "test" on my file with dup2 and printf. But nothing append to the file.
Thanks if you have a solution
答案 0 :(得分:2)
以下提议的代码
#include
语句。现在建议的代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT, 0777);
if( 0 > fichier )
{
perror( "open failed" );
exit( EXIT_FAILURE );
}
// IMPLIED else, open successful
if( dup2(fichier, 1) == -1 )
{
perror( "dup3 failed" );
exit( EXIT_FAILURE );
}
// implied else, dup2 successful
printf("test");
return 0;
}
在linux上这个命令:
ls -al ecrire.txt displays
-rwxrwxr-x 1 rkwill rkwill 4 Apr 19 18:46 ecrire.txt
这是浏览文件的内容:
less ecrire.txt
结果:
test
答案 1 :(得分:0)
您的示例适用于相应的标头,但它提供的文件权限仅允许root用户在此程序创建文件后读取该文件。所以我为用户添加了rw权限。我还删除了O_APPEND,因为你说你不想追加:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fichier = open("ecrire.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fichier, 1);
printf("test");
return 0;
}