2015-12-02 19 views
-4

这是我目前拥有的代码,但它似乎没有编译。任何帮助将非常感激。我需要创建一个程序,提示用户输入两个要读取的文件的名称。然后读取文件并显示统计信息

#include <stdio.h> 
main (void) 
{ 
    FILE *textfile1; 
    FILE *textfile2; 

    int c; 
    char Filename; 

    printf("Enter the name of text file:"); 
    scanf("%s", &Filename; 

    textfile1 = fopen(textfile1, "r"); 
    if (textfile1 == NULL) 
    { 
    printf("File not found"); 
    } 
    else 
    { 
    while (fscanf(textfile1, "%c", &textfile1) == 1) 
    { 
    printf("%c", textfile1); 
    } 
    fclose(textfile1); 
    } 
    } 
+2

什么是与你有什么事?它不以某种方式工作吗?请详细说明。 –

+0

不会编译,它有2个错误。一个是缺少类型说明符 - int假定。注意:C++不支持default-int。第二个错误是'FILE'* fopen(const char *,char *)':不能将参数1从FILE *'转换为'const char *' – benjohnson29

+0

'scanf(“%s”,&文件名;'缺少''' –

回答

1
#include <stdio.h> 
int main (void) /* you had better specify the return value explicitly */ 
{ 
FILE *textfile1; 
FILE *textfile2; 

int c; 
char Filename[1024]; /* allocate enough buffer to store the name */ 
char textfiledata1; /* add this to store the data from file */ 

printf("Enter the name of text file:"); 
scanf("%1023s", Filename); /* add), and other change including limit of length to read to avoid buffer overrun */ 

textfile1 = fopen(Filename, "r"); /* you have to pass the name. Do not pass the uninitialized file pointer! */ 
if (textfile1 == NULL) 
{ 
    printf("File not found"); 
} 
else 
{ 
    while (fscanf(textfile1, "%c", &textfiledata1) == 1) /* store the data from file to the file pointer? nonsense. */ 
    { 
    printf("%c", textfiledata1); 
    } 
    fclose(textfile1); 
} 
return 0; /* explicitly return something is a good practice */ 
} 
+0

谢谢你的回答。这可能是一个愚蠢的问题,但我可以问为什么你已经把数字1023与%s – benjohnson29

+0

限制读取的长度为1023(1024 - 1为终止空字符),以减少缓冲区溢出的风险。 – MikeCAT

+0

好的,谢谢。当我运行这段代码并输入文件名时,会弹出一个错误消息,说'project1已停止工作',这是我的代码或程序不能正常工作的错误 – benjohnson29

相关问题