【问题标题】:Write text into a .txt file in C将文本写入 C 中的 .txt 文件
【发布时间】:2016-01-08 07:36:44
【问题描述】:

我希望能够创建一个文件,然后将文本写入其中,但我不知道该怎么做。 这是我的一段代码:

FILE *note;
char name[100], *content;
printf("Write the name of your file.\n");
scanf("%s", &name);
note=fopen(name, "w");
printf("Write the content of your file\n");

接下来我该怎么做?

【问题讨论】:

  • 请在 fopen 等故障点后添加错误处理(可以返回 null )。之后 google fwrite
  • 或许别的页面会告诉你怎么做作业
  • scanf("%s", name); 中的 strings 不需要 & 运算符

标签: c file text


【解决方案1】:

您需要使用malloc分配内存,读取输入,并将其存储在分配的内存中。然后将其写入您打开的文件,最后释放分配的内存。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    FILE *note;

    char name[100], *content;

    content = (char*)malloc(1024);

    printf("Write the name of your file : ");

    scanf("%s",name);

    note = fopen(name, "w");

    printf("\nWrite the content of your file : ");

    scanf(" %[^\n]s",content);

    fprintf(note,"%s",content);

    printf("\nContent has been written to file!\n\n");

    free(content);

    fclose(note);

    return 0;
}

【讨论】:

    【解决方案2】:

    接下来我该怎么做?

    好吧,您应该为content 分配一些空间(尝试malloc()),然后将数据读入该空间(如果需要,可以通过realloc() 增加空间)。

    之后你需要将内容写入文件。

    最后用free()释放不再需要的空间。

    【讨论】:

      猜你喜欢
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多