打印并保存.txt

时间:2013-02-14 12:08:37

标签: c text save printf

我正在尝试做三件事:

  1. 加载.txt文件
  2. 将文件内容打印到控制台。
  3. 再次使用其他名称保存。
  4. #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;
    }
    

    我错过了控制台面板上的印刷文字;它不起作用,代码中缺少保存选项。我该怎么办?

2 个答案:

答案 0 :(得分:0)

问题在第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逐行阅读文件的更好方法。

答案 1 :(得分:0)

以下内容毫无意义:

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

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