2015-06-29 31 views
-1

我正在嘗試使用read()讀取txt文件並打印輸出。read()無法正常工作

文本文件有以下數字:

123 
456 
227 

和我的代碼如下所示

#include<stdio.h> 
#include<stdlib.h> 
#include <fcntl.h> 
#include<io.h> 

int main(int argc, char*argv[]){ 
    char* input; 
    char* output; 
    int fd; 
    int temp = 0; 




if(argc != 3){ 
     printf("Too Many or Too Few Arguments\n"); 
     exit(-1); 
    } 
    input = argv[1]; 
    output = argv[2]; 

    fd = open(input,O_RDONLY,0); 
    if(fd == -1){ 
     printf("Read Failed"); 
     exit(-1); 
    } 
    while(read(fd, &temp ,sizeof(int)) != 0){ 
     printf("%d\n", temp); 
    } 
    close(fd); 
} 

我試圖運行它,這是怎麼了我的輸出

221458993 
909456394 
842150410 
842150455 

做錯了?

+2

'read'不會將文本轉換爲二進制文件。你想要的是'fscanf'(或者你自己解析的'fgets')。 –

+3

221458993是第一行字節的十進制表示,十六進制中的字節爲0D333231,並轉換爲ASCII =「\ n321」 – alldayremix

回答

1

您需要執行formatted I/O才能獲取int值表示。

fscanf()或更好,fgets()是你的朋友。