Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将文本写入C中的.txt文件_C_File_Text - Fatal编程技术网

将文本写入C中的.txt文件

将文本写入C中的.txt文件,c,file,text,C,File,Text,我希望能够创建一个文件,然后将文本写入其中,但我不知道如何做到这一点。 这是我的一段代码: 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"); 接下来我该怎么办 接下来我该怎么办 那么,您应该为内容分配一些空

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

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");
接下来我该怎么办

接下来我该怎么办

那么,您应该为
内容
分配一些空间(尝试
malloc()
),然后将数据读入该空间(如果需要,可以
realloc()
来增加空间)

之后,您需要将内容写入文件


最后用
free()
释放不再需要的空间。您需要使用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;
}
#包括
#包括
#包括
内部主(空)
{
档案*注;
字符名称[100],*内容;
内容=(字符*)malloc(1024);
printf(“写下文件名:”);
scanf(“%s”,名称);
注=fopen(名称,“w”);
printf(“\n写入文件内容:”);
scanf(“%[^\n]s”,内容);
fprintf(注,“%s”,内容);
printf(“\n内容已写入文件!\n\n”);
免费(内容);
fclose(注);
返回0;
}

请在失败点后添加错误处理,如fopen(可以返回null)。在这之后,google fWrite可能会在另一个页面上告诉您如何做家务,您不需要
&
操作符来处理
scanf(“%s”,name)中的字符串