Skip to main content
 首页 » 编程设计

c之输入文本并保存到文件

2026年05月17日15mate10pro

以下函数创建一个新的文本文件,并允许用户输入要保存到文件中的文本。我无法解决的主要问题是 1) 允许单词之间有空格 2) 按回车键保存文本,而不是换行。

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");  
} 

请您参考如下方法:

使用fgets()而不是 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:

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);