2013-02-14 102 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