【问题标题】:trying to save the content in a custom named file尝试将内容保存在自定义命名文件中
【发布时间】:2020-03-18 19:44:49
【问题描述】:

我试图让用户使用自定义名称进行保存,但它似乎不起作用,当我对其进行硬编码时,它很好并且可以工作,但反之则不行。

char name[100];
    printf("\nEnter File name to save the file: ");
    fgets(name, 100, stdin);
    FILE *fLocation = fopen(name, "a+");//I can just put the complete path and name and it works
    if (fLocation == NULL){
        printf("Error, could't create the file\n");
        return;
    }

【问题讨论】:

  • fgets 还添加了一个尾随换行符,您可以在 fgets 调用后使用name[strcspn(name, "\n")] = 0; 将其删除,另请参阅这个很好的答案:stackoverflow.com/a/28462221(附加提示:您需要添加一个#include for strcspn)

标签: c file


【解决方案1】:

您也可以使用snprintf 打开或创建一个名为文件的用户

int main()
{
    char name[100];
    char buf[BUFSIZ];
    printf("\nEnter File name to save the file: ");
    scanf("%s", name);
    snprintf(buf, sizeof(buf), "%s.txt", name);//for text file add .txt to entered name
    FILE* fLocation = fopen(buf, "a+");
    if (fLocation == NULL)
    {
        printf("Error, could't create the file\n");
        return 0;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2015-01-10
    • 2015-10-25
    相关资源
    最近更新 更多