How do I write a file to a nonspecific user's desktop on C? [duplicate]

泪湿孤枕 提交于 2019-12-25 04:41:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!