![](/img/trans.png)
[英]Trying to find byte position where two files differ using file i/o read and write
[英]Using file i/o to read byte length
我試圖用以下代碼找到兩個不同文件的字節長度,但得到字節長度為1,這顯然是錯誤的。 從長遠來看,我正在嘗試比較每個文件的內存位置,並打印出它們的不同之處,如您所見。 所以我沒有到達任何地方,並做了printf
語句,看看問題可能在哪里。 因此,看起來好像我的長度沒有正確計算。
可能有助於我的問題的旁注 - 我發現這是為memcmp,但這是否意味着我不能使用!=
?:
如果返回值<0則表示str1小於str2
如果返回值> 0則表示str2小於str1
如果返回值if = 0則表示str1等於str2
請幫助!
void compare_two_binary_files(int f1, int f2)
{
ssize_t byte_read_f1, byte_read_f2, length, numRead, bob, length2;
char buf1[BUF_SIZE], buf2[BUF_SIZE], a[100], b[100], counter[100];
int count = 0, b_pos1, b_pos2;
while ((byte_read_f1 = read(f1, buf1, sizeof buf1) > 0) && (byte_read_f2 = read(f2, buf2, sizeof buf2) >0)) {
length = byte_read_f1;
length2 = byte_read_f2;
printf("F1 byte length:%o\n", length);
printf("F2 byte length:%o\n", length2);
ssize_t len = byte_read_f1 <byte_read_f2 ? byte_read_f1 : byte_read_f2;
b_pos1 = memcmp(buf1, buf2, len);
printf("Memcmp: %d\n", b_pos1);
if (memcmp(buf1, buf2, len) != 0){ // use memcmp for speed
ssize_t i;
for (i = 0; i<len; i++){
if (buf1[i] != buf2[i]) break;
}
}
我認為在while條件下有一個錯誤:
while ((byte_read_f1 = read(f1, buf1, sizeof buf1) > 0) &&
(byte_read_f2 = read(f2, buf2, sizeof buf2) >0))
其中分配read(f1, buf1, sizeof buf1) > 0
(結果為真= 1)以byte_read_f1
因此對於byte_read_f2
。
這可以幫到你嗎?
評論意見如何:
正確的表格將是:
while (((byte_read_f1 = read(f1, buf1, sizeof buf1)) > 0) &&
((byte_read_f2 = read(f2, buf2, sizeof buf2)) >0))
>
因此優先級高於=
if ((byte_read_f1 = read(f1, buf1, sizeof buf1) > 0) && ...)
相當於
if (byte_read_f1 = (read(f1, buf1, sizeof buf1) > 0) && ...)
如果至少讀取了一個字節, byte_read_f1
1
分配給byte_read_f1
。
你想要的是什么
if ((byte_read_f1 = read(f1, buf1, sizeof buf1)) > 0 && ...)
如果您的程序從常規文件以外的其他文件(例如標准輸入)讀取,那么您還必須考慮read()返回的字節數少於請求的情況。
對於常規文件,read()始終返回請求的字節數,當然只有例外的文件結尾處。 因此,如果文件的長度不同,那么在某些時候, read(f1, ...)
將返回與read(f2, ...)
不同的量,或者一個返回零而另一個不返回。
如果fseek()到每個文件的末尾,並查詢文件位置偏移量? fstat()調用或類似的東西甚至可以直接告訴你大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.