gpt4 book ai didi

c - 在 C 中将文件写入用户的 HOME 目录

转载 作者:行者123 更新时间:2023-12-03 23:15:09 25 4
gpt4 key购买 nike

我正在尝试将 .txt 文件写入用户的 HOME 目录。

我试过了:

char str[] = "TEST";
char* file = strcat(getenv("HOME"), "/dataNumbers.txt"); //I am concatenating the user's home directory and the filename to be created.
myFile = fopen(file,"w");
fwrite(str , 1 , sizeof(str) , myFile );

但是,这不会创建文件。

最佳答案

你不能strcat()到环境变量。你需要另一个缓冲区:

char file[256]; // or whatever, I think there is a #define for this, something like PATH_MAX
strcat(strcpy(file, getenv("HOME")), "/dataNumbers.txt");
myFile = fopen(file,"w");

编辑 要解决以下评论之一,您应该首先确保要连接的数据不会溢出 file缓冲,或动态分配它 - 之后不要忘记释放它。

关于c - 在 C 中将文件写入用户的 HOME 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com