Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.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 输入文本并保存到文件_C_Linux - Fatal编程技术网

C 输入文本并保存到文件

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

以下函数创建一个新的文本文件,并允许用户输入要保存到该文件中的文本。我解决的主要问题是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(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);