2017-04-11 69 views
0

我正在做一個關於使用UNIX系統命令的練習,我試圖從逐個字符開始讀取兩個文件。當字符不同時,程序應該從兩個文件中打印剩餘的字符以及字符開始不同的位置。初始化的字符數組指向相同的內存

Ex。 ex1.txt有「我的名字是卡爾」和ex2.txt有「我的名字是約翰」。 程序在ex1中打印「Carl」,在ex2中打印「John」。

我的程序執行讀取和位置信息,但是在初始化讀取緩衝區並對其進行比較時遇到問題。

我正在初始化兩個大小的字符數組,但是當我使用讀取方法變量buf2獲取當前位置的兩個文件字符。這暗示bufbuf2指向相同的內存。我應該爲我的char數組動態分配內存,還是有其他方法可以做到這一點?

Moreso:如果buf2包含兩個字符(如果它的大小僅爲1),該怎麼辦?輸入

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <string.h> 

#define B_SIZE 1 

void err_exit(char *msg) { 
    perror(msg); 
    exit(EXIT_FAILURE); 
} 

int main (int argc, char** argv) { 
int file, file2, size, size2; 
char buf[B_SIZE], buf2[B_SIZE]; 
off_t pos, pos2; 

if (argc != 3) err_exit("Enter two files as arguments"); 
if ((file = open(argv[1], O_RDONLY)) == -1) err_exit("Cant open file 1"); 
if ((file2 = open(argv[2], O_RDONLY)) == -1) err_exit("Cant open file 2"); 

size = lseek(file, B_SIZE, SEEK_END); 
size2 = lseek(file2, B_SIZE, SEEK_END); 
pos = lseek(file, 0, SEEK_SET); 
pos2 = lseek(file2, 0, SEEK_SET); 

printf("\n\nPOS: %d, %d SIZE: %d, %d\n", pos, pos2, size, size2); 
pread(file, &buf, B_SIZE, pos); 
pread(file2, &buf2, B_SIZE, pos2); 

while(((pos = lseek(file, B_SIZE, SEEK_CUR)) < size) 
&& ((pos2 = lseek(file2, B_SIZE, SEEK_CUR)) < size2)) 
{ 
    printf("Searching first different char: POS: %d\nChar: %s, %s\n", pos, buf, buf2); 
    printf("Is buf same as buf2: %d\n", (strcmp(buf, buf2))); 
    pread(file, &buf, B_SIZE, pos); 
    pread(file2, &buf2, B_SIZE, pos2); 

} 

if ((size == size2) && (pos == pos2)){ 
    printf("Files are the same\n"); 
} else { 
    printf("\nNot same anymore. POS: %d\n", pos); 
    printf("Print file 1 starting from this position\n"); 
    while(((pos = lseek(file, B_SIZE, SEEK_CUR)) < size)){ 
     pread(file, &buf, B_SIZE, pos); 
     printf("%s", buf); 
    } 
    printf("\n\nPrint file 2 starting from this position\n"); 
    while(((pos2 = lseek(file2, B_SIZE, SEEK_CUR)) < size2)){ 
     pread(file2, &buf, B_SIZE, pos2); 
     printf("%s", buf); 
    } 
} 




close(file); 
close(file2); 
return 0; 
} 

例子:
Output of program

+1

更快且更簡單。C沒有邊界檢查。走出界限導致*未定義的行爲*。 –

+1

您的緩衝區只有1個字符大小。這隻能保存空字符串(''\ 0'')和'strcmp'在其中的任何其他字符串中是不可能的(在該大小的緩衝區中不能有任何其他字符串)。 –

回答

1

您違反了該字符串的概念。 實施例:

strcmp(buf, buf2) 

字符串必須被零終止。如果您將char*傳遞給期望字符串的函數,則您必須必須確保它指向以零結尾的字符串。

你的緩衝區的大小隻有1,所以沒有零終止的餘地。因此,您會執行非法函數調用並且具有未定義的行爲。

你可以試試這個:

char buf[B_SIZE+1], buf2[B_SIZE+1]; 
buf[B_SIZE] = '\0'; 
buf2[B_SIZE] = '\0'; 

,但如果你想讀的字符按字符爲什麼不讀入字符變量。可以使用==來比較字符,其比strcmp