0

私は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;
}

コンソール パネルに印刷されたテキストがありません。機能せず、コードに保存オプションがありません。私は何をすべきか?

4

2 に答える 2

0

次のことは意味がありません。

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

読み取り用にファイルを開いた場合、なぜそのファイルに書き込もうとしているのですか?ファイル()から読み取り、man fgetsstdoutに書き込みます。

于 2013-02-14T12:11:07.147 に答える
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を使用して行ごとに行うことです。

于 2013-02-14T12:10:48.750 に答える