C 使用dup2和printf写入文件很麻烦
我对这个简单的代码有一个问题:C 使用dup2和printf写入文件很麻烦,c,printf,dup,C,Printf,Dup,我对这个简单的代码有一个问题: 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; } 我只需要用dup2和printf在我的文件上写“test”。但文件中没有附加任何内容 谢谢,如果您有一个解决方案您的示例确实可以使用适当的标题
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;
}
我只需要用dup2和printf在我的文件上写“test”。但文件中没有附加任何内容
谢谢,如果您有一个解决方案您的示例确实可以使用适当的标题,但是它提供了文件权限,仅允许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;
}
#包括
#包括
#包括
int main(){
int fichier=open(“ecrire.txt”,O_WRONLY | O|u CREAT,S|u IRUSR | S|u IWUSR);
dup2(fichier,1);
printf(“测试”);
返回0;
}
以下建议的代码
#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;
}
要浏览文件的内容,请执行以下操作:
less ecrire.txt
结果:
test
发布的代码无法编译!除其他事项外,它缺少所需的
#include
语句:`include#include#include`对于open()
函数,#include
对于函数:dup2()
#包含函数:`printf()调用open()
时,始终检查(0>=)返回值以确保操作成功。调用dup2()
时,始终检查返回值(!=-1)以确保操作成功。可能的重复建议使用这种形式的open()
语句:int open(const char*pathname,int标志,mode\u t mode)代码>以便可以读取生成的文件,等等
test