2017-09-14 99 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] ...因此,您將讀出文件中未包含的元素,實際上超出了數組邊界(導致垃圾或其他東西)。

相關問題