C 输入文本并保存到文件
以下函数创建一个新的文本文件,并允许用户输入要保存到该文件中的文本。我解决的主要问题是1)允许单词之间留空格2)按enter键保存文本,而不是转到新行C 输入文本并保存到文件,c,linux,C,Linux,以下函数创建一个新的文本文件,并允许用户输入要保存到该文件中的文本。我解决的主要问题是1)允许单词之间留空格2)按enter键保存文本,而不是转到新行 void new_file(void) { char c[10000]; char file[10000]; int words; printf("Enter the name of the file\n"); scanf("%123s",file); strcat(fi
void new_file(void)
{
char c[10000];
char file[10000];
int words;
printf("Enter the name of the file\n");
scanf("%123s",file);
strcat(file,".txt");
FILE * pf;
pf = fopen(file, "w" );
if (!pf)
fprintf( stderr, "I couldn't open the file.\n" );
else
{
printf("Enter text to be saved\n");
scanf("%s", c);
fprintf(pf, "%s", c);
}
fclose(pf); // close file
printf("\n\nReturning to main menu...\n\n");
}
使用而不是scanf()
从用户处获取输入文本
为此,请更换此线路
scanf("%s", c);
使用以下代码:
if (NULL != fgets(c, sizeof(c), stdin))
{
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
}
要允许用户读入多行代码,请在上面的代码周围放置一个循环。为此,您需要定义一个条件,告知程序停止循环: 以下示例在输入单点“.”并按return键时停止以行读取:
“\n”
用作scanf
的终止符。是否需要另一个终止符,例如“#”
:while(getchar!=”#“)…
?@bitfidlingcodemonkey:很好。扩展我的答案,使用经典的“点输入”选项结束阅读。@alk-hmm-wird即使我用a完成一个句子,我仍然可以转到下一行。您可能希望使用符号(-g
)编译,然后使用调试器(gdb)跟踪代码。我稍微修改了我的答案。
do
{
if (NULL != fgets(c, sizeof(c), stdin))
{
if (0 == strcmp(c, ".\n")) /* Might be necessary to use ".\r\n" if on windows. */
{
break;
}
fprintf(pf, "%s", c);
}
else
{
if (0 != ferror(stdin))
{
fprintf(stderr, "An error occured while reading from stdin\n");
}
else
{
fprintf(stderr, "EOF was reached while trying to read from stdin\n");
}
break;
}
} while (1);