我正在尝试将.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 );
但是,这不会创建文件。
答案 0 :(得分:4)
您错误地使用了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);
file
现在将包含连接的路径和文件名。
显然,这可以写得更干净。我只是想直截了当。
答案 1 :(得分:4)
您不能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
缓冲区,或动态分配 - 不要忘记免费之后它。
答案 2 :(得分:1)
Strings in C are not like other strings in other high-level languages; that is, You have to allocate all the space for them yourself. When using c-string functions, you need to ensure that you have enough memory allocated for the resultant strings, by either reserving enough space on the stack (i.e. char filename[HOPEFULLY_ENOUGH]) or via the heap (malloc() and friends). You cannot count on getenv
to return a string with enough space for you to concatenate to;
Here's a complete program from start to finish that does what you want to do (minus some pedantic error checking):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *filename = "/dataNumbers.txt";
char *writeString = "TEST";
char *home_dir = getenv("HOME");
char *filepath = malloc(strlen(home_dir) + strlen(filename) + 1);
strncpy(filepath, home_dir, strlen(home_dir) + 1);
strncat(filepath, filename, strlen(filename) + 1);
printf("%s\n", filepath);
FILE *myFile = fopen(filepath, "w");
fwrite(writeString, 1, strlen(writeString), myFile);
fclose(myFile);
free(filepath);
return 0;
}
strncpy will copy the string plus the null terminator (that's the reason for the +1
). strncat will begin concatenation at the null terminator and the resultant concatenated string itself must be null-terminated (hence the +1
in the third argument to strncat).
I use malloc and free because it's hard to know exactly the length of the full path to your file. You could go with something enormous (like char[4096]) but that seems wasteful, doesn't it? malloc() allows you to reserve exactly the amount of memory you need. No more, and no less.
You can also do the string concatenation using the snprintf function. I include this only for your personal enrichment, and sometimes it's nice to have multiple ways to do the same thing, even though strcpy and strcat will make your intentions much more clear to readers of your code:
char *filename = "/dataNumbers.txt";
char *writeString = "TEST";
char *home_dir = getenv("HOME");
size_t size = strlen(home_dir) + strlen(filename) + 1;
char *filepath = malloc(size);
snprintf(filepath, size, "%s%s", home_dir, filename);
Hope this helps!