【问题标题】:How to create a new text file in C?如何在 C 中创建一个新的文本文件?
【发布时间】:2015-11-30 21:20:39
【问题描述】:

我正在创建一个程序,它从一个文本文件中读取数据并将其大小更改为大写或小写,然后将该数据存储在一个新文件中。我已经搜索了互联网,但我找不到如何创建一个新的文本文件。

#include <stdio.h>
int main(void) {

        FILE *fp = NULL;

        fp = fopen("textFile.txt" ,"a");

        char choice;

        if (fp != NULL) {

                printf("Change Case \n");
                printf("============\n");
                printf("Case (U for upper, L for lower) : ");
                scanf(" %c", &choice);
                printf("Name of the original file : textFile.txt \n");
                printf("Name of the updated file : newFile.txt \n");

我知道这是不完整的,但我不知道如何创建一个新的文本文件!

【问题讨论】:

  • a 用于“追加”。如果文件存在,它将被附加到。您可能需要 w 进行写入 - 如果文件存在,它将被截断,然后您重新开始。
  • Marc 是正确的,如果您不希望出现不可预测的行为,请务必在最后关闭。
  • fopen 如果您打开一个新文件进行写入,则会创建该文件,例如:stackoverflow.com/questions/9840629/…
  • 您找不到互联网?

标签: c text-files


【解决方案1】:
fp = fopen("textFile.txt" ,"a");

这是创建文本文件的正确方法。问题在于您的 printf 语句。你想要的是:

fprintf(fp, "Change Case \n");
...

【讨论】:

  • (你应该检查fp != NULL,但你已经这样做了);最后别忘了致电fclose(fp);。您有时可能想致电fflush
  • fopen() 的“at”模式不是 C 标准中 7.21.5.3 fopen 函数的一部分。 open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
  • 什么是 fprintf(fp, "change case \n");做?谢谢
  • @HassenFatima,它将“更改大小写”写入处理 fp 指向的文件中。与普通的printf 不同,它写入标准输出。
【解决方案2】:
#include <stdio.h>
#define FILE_NAME "text.txt"

int main()
{
    FILE* file_ptr = fopen(FILE_NAME, "w");
    fclose(file_ptr);

    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    相关资源
    最近更新 更多