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

Han*_*fei 3 c file-io file output

我正在尝试将 .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 );
Run Code Online (Sandbox Code Playgroud)

但是,这不会创建文件。

Dav*_*zer 5

您使用strcat不当。

 char *file;
 char *fileName = "/dataNumbers.txt";

 file = malloc(strlen(getenv("HOME") + strlen(fileName) + 1); // to account for NULL terminator
 strcpy(file, getenv("HOME"));
 strcat(file, fileName);
Run Code Online (Sandbox Code Playgroud)

file 现在将包含连接的路径和文件名。

显然,这可以写得更干净。我只是想变得非常直截了当。


use*_*421 5

你不能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");
Run Code Online (Sandbox Code Playgroud)

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