我正在做一個關於使用UNIX系統命令的練習,我試圖從逐個字符開始讀取兩個文件。當字符不同時,程序應該從兩個文件中打印剩餘的字符以及字符開始不同的位置。初始化的字符數組指向相同的內存
Ex。 ex1.txt有「我的名字是卡爾」和ex2.txt有「我的名字是約翰」。 程序在ex1中打印「Carl」,在ex2中打印「John」。
我的程序執行讀取和位置信息,但是在初始化讀取緩衝區並對其進行比較時遇到問題。
我正在初始化兩個大小的字符數組,但是當我使用讀取方法變量buf2
獲取當前位置的兩個文件字符。這暗示buf
和buf2
指向相同的內存。我應該爲我的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;
}
例子:
更快且更簡單。C沒有邊界檢查。走出界限導致*未定義的行爲*。 –
您的緩衝區只有1個字符大小。這隻能保存空字符串(''\ 0'')和'strcmp'在其中的任何其他字符串中是不可能的(在該大小的緩衝區中不能有任何其他字符串)。 –