问题
I wrote a program and I wanted it to write a file to the Desktop. I figured out how to write it to mine, but I want it to be able to go to anybody's desktop (windows).
Is there a way to make the path name more dynamic so it can work on anybody's desktop?
This is a sample:
void add(void)
{
FILE *fp;
fp = fopen("C:\\Users\\Jones\\Desktop\\test.txt", "w+");
float num1;
float num2;
float sum;
printf("Enter first number: ");
num1 = getNum();
printf("Enter second number: ");
num2 = getNum();
sum = num1 + num2;
printf("%.1f + %.1f = %.1f\n", num1, num2, sum);
fprintf(fp, "Num1: %.1f\nNum2: %.1f\nSum: %.1f ", num1, num2, sum);
fclose(fp);
while(getchar() != '\n')
{
continue;
}
}
回答1:
Yes. Use sprintf
. It's like fprintf
but for strings.
char fname[256];
sprintf(fname, "C:\\Users\\%s\\Desktop\\test.txt", "Jones");
fopen(fname, ...
来源:https://stackoverflow.com/questions/26644618/how-do-i-write-a-file-to-a-nonspecific-users-desktop-on-c