c - 打印并保存.txt

标签 c text save printf

我正在尝试做三件事:

  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");
fprintf(file, "%s", line);

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

关于c - 打印并保存.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874534/

相关文章:

HTML CSS 将段落中的部分文本居中

c - 这个 C 函数是什么意思?函数指针?

C:string 在 malloc 和 strcpy 之间被损坏

c++ - 优化编译器如何决定何时以及展开多少循环?

java - 在java中的特定位置拆分字符串

java - 在java中保存新创建的对象

c - 如何将 C for 循环体与 GCC 对齐?

excel - 寻找一个公式检查两列的值并返回一个值

objective-c - iOS:问题保存照片

Python 保存到映射共享驱动器时出错