2017-09-14 100 views
0

我是C新手,正在尝试完成一项任务。程序应该将文件名作为命令行参数,然后打印文件内容。我的程序打印文本混乱而不是文件中的实际文本。将文本文件中的字符添加到数组中

我已经在互联网上搜索了所有关于我的问题的示例/答案,并且仍然卡住!

我在做什么错?如果能够得到帮助,请修改我的代码,而不是编写新的代码,以便我能更轻松地理解。

int main() 
{ 
    char fileName[20]; 
    int *buffer; 
    int size; 

    // ask for file name and take input. 
    printf("Enter file name: ");    
    scanf("%s", fileName); 

    // open file in read mode. 
    FILE *fp; 
    fp = fopen(fileName, "r");   

    // If no file, show error. 
    if(fp == NULL)     
    { 
     printf("Error: Can't open file.\n");   
     return 1; 
    } 

    // count characters in file with fseek and put into size, then move the 
    // position of the file back to the beginning. 
    fseek(fp, 0, SEEK_END); 
    size = ftell(fp); 
    rewind(fp); 

    // allocate buffer and read file into buffer. 
    buffer = malloc(size+1); 
    fread(buffer, 1, size, fp); 

    // close the file. 
    fclose(fp); 

    // for loop reading array one character at a time. 
    for(int x = 0; x < size; x++) 
    {    
     printf("%c", buffer[x]); 
    } 

    return 0; 
} 
+1

始终保持缓冲区溢出的警惕。 20个字符的缓冲区非常小。如果编译代码时出现故障,*打开调试器*。 – tadman

+2

'int * buffer' - >'char * buffer' –

+0

回答

2

您使用了错误的数据类型为字符读,即使用int *buffer,但你应该使用char *buffer

使用int *buffer时,像printf("%c",buffer[x])这样的访问将以整数数组的形式访问缓冲区;一个整数的大小可能是4,这样buffer[1]将寻址缓冲区中的第4个字节,第8个等待地址为buffer[2] ...因此,您将读出文件中未包含的元素,实际上超出了数组边界(导致垃圾或其他东西)。

相关问题