【问题标题】:Print and save .txt打印并保存 .txt
【发布时间】:2013-02-14 12:08:37
【问题描述】:

我正在尝试做 3 件事:

  1. 加载 .txt 文件
  2. 将文件内容打印到控制台。
  3. 用其他名称再次保存。
#include <stdio.h>
#include <stdlib.h>


int main(int argc, char** argv) {

char text[500]; /* Create a character array that will store all of the text in the file */
char line[100]; /* Create a character array to store each line individually */

 int  inpChar; 

FILE *file; /* Create a pointer to the file which will be loaded, to allow access to it */
char fileName[100]; /* Create a character array to store the name of the file the user want to load */


do {
printf("enter menu: [l]oad - [s]ave - [p]rint\n");
scanf("%c", &inpChar);
    } 
    while((inpChar != 'l') && (inpChar != 's') && (inpChar !="p"));

if((inpChar == 'l'))
{
 printf("Enter the name of the file containing ship information: ");
}
scanf("%s", fileName);

/*Try to open the file specified by the user. Use error handling if file cannot be found*/
file = fopen(fileName, "r"); /* Open the file specified by the user in 'read' mode*/
if(file == NULL){
    printf("The following error occurred.\n");
}
else {
    printf("File loaded. \n"); /* Display a message to let the user know 

                          * that the file has been loaded properly */

}

 do {
printf("enter menu: [l]oad - [s]ave - [p]rint\n");
scanf("%c", &inpChar);
    } 


while((inpChar != 'l') && (inpChar != 's') && (inpChar !='p'));
if((inpChar == 'p'))
{
file = fopen(fileName, "r");
fprintf(file, "%s", line);
fclose(file);

}

return 0;
}

我缺少控制台面板上的打印文本;它不起作用,并且代码中缺少保存选项。我该怎么办?

【问题讨论】:

  • file = fopen(fileName, "r"); if(file == NULL){ perror( filename ); }
  • 定义“它不起作用”..
  • 您能否将代码示例缩减为仅包含不起作用的代码,而不会像用户界面那样混乱?
  • 我在您的代码中发现了很多问题,太多无法发布细节。您应该更好地解决问题...编写一个具有一个功能的程序来加载您的文件(首先使用固定的文件名)。让您满意(请注意,您粘贴的代码对输入文件进行了准确的 zero 读取!)。然后使用另一个将内容打印到屏幕的功能修改程序。 (您的代码也不会这样做,考虑到您还没有读取文件,这很好。)最后,将文件保存到其他位置的例程。一旦这些都奏效了,然后考虑提示该做什么。
  • 好的,但打印功能仍然存在同样的问题!。

标签: c text save printf


【解决方案1】:

以下内容毫无意义:

file = fopen(fileName, "r");
fprintf(file, "%s", line);

如果您打开一个文件进行读取,您为什么要尝试写入它?您想从文件中读取 (man fgets),然后写入标准输出。

【讨论】:

  • 从文件中读取行并将它们打印到标准输出。使用fgets 从文件中读取一行,然后使用printf 打印。
  • if((inpChar == 'p')) { fgets ( line ,9999,file); printf(行,文件); fclose(文件);
  • @Haido 如果您当前的代码只读取一行,请考虑将其放入循环中。
  • 我尝试使用 while 循环,所以我现在可以工作了,非常感谢;)
【解决方案2】:

问题在第 10 行:

int inpChar;

应该是

char  inpChar;

第 23 行的错误:

while((inpChar != 'l') && (inpChar != 's') && (inpChar !="p"));

应该是

'p'



您必须将文件读入数组。 如果文件不超过 10000 个字符,这是一种原始方法。

char all[10000];
fread (all ,1,9999,file);
printf("%s", all);

读取文件的更好方法是逐行使用fgets

【讨论】:

  • 好的,但仍然是同样的问题,我想先加载文件,然后当我输入 p 时显示在控制台上的文本文件,所以当我加载文本文件并打印它时,我得到“- ------ " ,不是我在文本文件中的内容。!
  • 是的,现在可以了,非常感谢;)
  • 但是我怎样才能用另一个文本文件名再次保存它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2017-11-01
相关资源
最近更新 更多