如何檢查一個文件是否與使用Unix C的其他文件相同(具有相同的內容)?我的意思是,當我不能使用fopen, fread, fclose
而只是open, read, close
?我感興趣的答案,它展示瞭如何做到這一點只有在Unix的C.如何檢查Unix C中的文件是否相同?
我寫了一個程序,將文件複製到另一個,但不知道如何檢查,如果它們是相同的:/:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
const char *in_filename = "in.txt", *out_filename = "out.txt";
int in_fd, out_fd, bytes_read, bytes_written;
int buffsize = 512;
char buffer[512];
int success = 0;
in_fd = open(in_filename, O_RDONLY);
if (in_fd == -1)
return -1;
out_fd = open(out_filename, O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
if (out_fd == -1)
return -1;
for(;;)
{
bytes_read = read(in_fd, buffer, buffsize);
if (bytes_read > 0)
{
bytes_written = write(out_fd, buffer, bytes_read);
if(bytes_written < 0)
return -1;
}
else
{
if (bytes_read == 0)
{
if (close(in_fd) < 0)
return -1;
if (close(out_fd) < 0)
return -1;
success = 1;
break;
}
else if (bytes_read == -1)
{
break;
return -1;
}
}
}
if(success)
fprintf(stdout, "%s", "Success!\n");
return 0;
}
繼承人是我的嘗試:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
const char *in_filename = "in.txt", *out_filename = "out.txt";
int in_fd, out_fd, bytes_read_in, bytes_read_out;
int buffsize = 512;
char in_buffer[512], out_buffer[512];
int the_same = 0;
in_fd = open(in_filename, O_RDONLY);
if (in_fd == -1)
return -1;
out_fd = open(out_filename, O_RDONLY);
if (out_fd == -1)
return -1;
for(;;)
{
bytes_read_in = read(in_fd, in_buffer, buffsize);
if (bytes_read_in > 0)
{
bytes_read_out = read(out_fd, out_buffer, buffsize);
if(bytes_read_out > 0)
{
int i = 0;
for(i=0; i<buffsize; i++)
{
if(in_buffer[i] != out_buffer[i])
the_same = 0;
}
the_same = 1;
}
}
else
{
if (bytes_read_in == 0)
{
if (close(in_fd) < 0)
return -1;
if (close(out_fd) < 0)
return -1;
break;
}
else if (bytes_read_in == -1)
{
break;
return -1;
}
}
}
if(the_same)
fprintf(stdout, "%s", "Files are the same!\n");
return 0;
}
但它表明文件是相同的,而對方不:(
你有沒有嘗試過某些東西並卡住了某個地方? – Rohan
@Rohan:yup我寫了一個程序,將一個文件複製到另一個文件,但不知道如何檢查它們是否相同:/ – Katie
檢查文件的大小相同,然後打開這兩個文件並逐字節比較。 –