2013-02-14 97 views
0

我試圖做3兩件事:打印和保存的.txt

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

我缺少的控制檯面板上的打印文本;它沒有工作,代碼中沒有保存選項。我該怎麼辦?

+0

'file = fopen(fileName,「r」); if(file == NULL){perror(filename); }' – 2013-02-14 12:10:06

+0

Define「it does not work」.. – KBart 2013-02-14 12:10:07

+0

您是否可以減少代碼示例以僅包含不工作的代碼,而不會像用戶界面那樣混亂? – millimoose 2013-02-14 12:15:07

回答

0

下是沒有意義的:

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

如果打開一個文件進行讀取,爲什麼你試圖寫它?你想從文件中讀取(man fgets),然後寫入標準輸出。

+0

那麼我應該怎麼辦?從文件中讀取 – NoWorries 2013-02-14 12:22:04

+0

線,把它們打印到標準輸出。使用'fgets'來讀取文件中的一行,然後使用'printf'打印。 – 2013-02-14 12:27:48

+0

確定,但我的代碼只是讀第林è? – NoWorries 2013-02-14 13:11:59

0

的問題是在第10行:

int inpChar; 

應該在23行

char inpChar; 

錯誤:

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

應該

'p' 



您必須將文件讀入數組。 如果文件長度不超過10000個字符,這是一個原始的方法。

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

更好的方法來讀取您的文件將使用fgets逐行。

+0

好吧,但它仍然是同樣的問題,我想先加載文件,然後當我輸入p文本文件顯示在CONSOL,所以當我加載文本文件並打印它,我得到「 - ------「,不是我在文本文件 – NoWorries 2013-02-14 12:19:44

+0

是的,它現在worsks非常感謝你。!) – NoWorries 2013-02-14 12:40:06

+0

屁股我怎麼能再次保存與另一個文本文件名 – NoWorries 2013-02-14 12:41:10