用C语言将字符串写入文本文件会使字符位消失

用C语言将字符串写入文本文件会使字符位消失,c,text-files,C,Text Files,我的目标是能够将字符串写入一个文件,并显示整个内容,而不仅仅是其中的一部分。问题是,当我签入文本文件时,我输入的字符串中有一些特许权 这是我的密码: #include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("file.txt", "w"); if (fp == NULL) { printf("Error opening file!\n");

我的目标是能够将字符串写入一个文件,并显示整个内容,而不仅仅是其中的一部分。问题是,当我签入文本文件时,我输入的字符串中有一些特许权

这是我的密码:

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

int main()
{

    FILE *fp = fopen("file.txt", "w");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }
    char comment[100];
    fp=fopen("/home/matthew/Desktop/BBE.txt","w");
    printf("Enter, String: ");
    scanf("%s", &comment);
    fgets(comment, sizeof comment, stdin);
    fputs(comment,fp); 
}
但当我检查文本文件时,我得到以下信息:

 World

我这里漏了一个字,不知道为什么,请帮忙

去掉scanf,因为它正在读取输入的第一个字,所以代码如下所示:

char comment[100];
fp=fopen("/home/matthew/Desktop/BBE.txt","w");
printf("Enter, String: ");
fgets(comment, sizeof comment, stdin);
fputs(comment,fp);

您正在使用FGET和scanf从用户处读取输入。你不需要两者兼而有之。此外,在scanf中,您传递的是字符数组第一个元素的地址,而不仅仅是第一个元素的地址(在scanf中使用“comment”而不是“&comment”)。写入后也不会关闭文件。请尝试以下操作:

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

int main()
{

FILE *fp = fopen("/home/matthew/Desktop/BBE.txt", "w");

if (fp == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}
char comment[100];
fp=fopen("file.txt","w");
printf("Enter, String: ");
scanf("%s", comment); //Don't pass &comment. Just pass 'comment' - the addr of zeroth element.
//fgets(comment, sizeof comment, stdin);
fputs(comment,fp);
fclose(fp);

}
#包括
#包括
int main()
{
文件*fp=fopen(“/home/matthew/Desktop/BBE.txt”,“w”);
如果(fp==NULL)
{
printf(“打开文件时出错!\n”);
出口(1);
}
char注释[100];
fp=fopen(“file.txt”,“w”);
printf(“输入,字符串:”);
scanf(“%s”,comment);//不传递&comment。只传递'comment'-第0个元素的地址。
//fgets(评论、评论大小、标准文本);
FPUT(评论,fp);
fclose(fp);
}
当您必须在其中一个文件中写入来自stdin的输入时,为什么在这里使用两个文件?下面的一段代码将帮助您获得所需的输出。最好在这里使用get()而不是fgets(),因为您并没有从文件中读取输入。此外,完成后不要忘记关闭文件。希望这有帮助

#包括
#包括
#包括
int main()
{
文件*fp;
字符注释[100]={0};
fp=fopen(“tempfile.txt”,“w”);
如果(fp==NULL)
{
printf(“打开文件时出错!\n”);
出口(1);
}
printf(“输入字符串:”);
获取(注释);
fwrite(注释,sizeof(注释),1,fp);
fclose(fp);
返回0;
}

下定决心:
scanf
fgets
。这些是读取字符串的替代方法。(要读取包含空格的行,请保留
fgets
并删除
scanf
#include <stdio.h>
#include <stdlib.h>

int main()
{

FILE *fp = fopen("/home/matthew/Desktop/BBE.txt", "w");

if (fp == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}
char comment[100];
fp=fopen("file.txt","w");
printf("Enter, String: ");
scanf("%s", comment); //Don't pass &comment. Just pass 'comment' - the addr of zeroth element.
//fgets(comment, sizeof comment, stdin);
fputs(comment,fp);
fclose(fp);

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

int main()
{

    FILE *fp;
    char comment[100] = {0};
     fp=fopen("tempfile.txt","w");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    printf("Enter String: ");
    gets(comment);
    fwrite(comment, sizeof(comment), 1, fp) ;

    fclose(fp);

    return 0;
}