Files
zvfs/test/test_two_files.c
2026-03-02 07:27:48 +00:00

79 lines
2.4 KiB
C
Executable File

#include "test_utils.h"
static int test_two_files(const char *path_a, const char *path_b)
{
printf("\n=== test_two_files ===\n");
int fd_a = open(path_a, O_CREAT | O_RDWR | O_TRUNC, 0644);
if (fd_a < 0) { perror("open A"); return 1; }
int fd_b = open(path_b, O_CREAT | O_RDWR | O_TRUNC, 0644);
if (fd_b < 0) { perror("open B"); return 2; }
printf("fd_a=%d fd_b=%d\n", fd_a, fd_b);
const char *data_a = "File-A: Hello World!";
const char *data_b = "File-B: Goodbye World!";
if (write(fd_a, data_a, strlen(data_a)) < 0) { perror("write A"); return 3; }
if (write(fd_b, data_b, strlen(data_b)) < 0) { perror("write B"); return 4; }
printf("write A: %s\n", data_a);
printf("write B: %s\n", data_b);
lseek(fd_a, 0, SEEK_SET);
lseek(fd_b, 0, SEEK_SET);
char buf_a[64] = {0};
char buf_b[64] = {0};
ssize_t r_a = read(fd_a, buf_a, sizeof(buf_a));
ssize_t r_b = read(fd_b, buf_b, sizeof(buf_b));
printf("read A: %zd bytes: %.*s\n", r_a, (int)r_a, buf_a);
printf("read B: %zd bytes: %.*s\n", r_b, (int)r_b, buf_b);
int ok = 1;
if (strncmp(buf_a, data_a, strlen(data_a)) != 0) {
printf("FAIL: A content mismatch!\n");
ok = 0;
}
if (strncmp(buf_b, data_b, strlen(data_b)) != 0) {
printf("FAIL: B content mismatch!\n");
ok = 0;
}
if (ok) {
printf("PASS: both files read back correctly\n");
}
lseek(fd_a, 0, SEEK_END);
if (write(fd_a, "[A-TAIL]", 8) != 8) { perror("append A"); return 5; }
lseek(fd_b, 8, SEEK_SET);
if (write(fd_b, "Hi! ", 7) != 7) { perror("overwrite B"); return 6; }
lseek(fd_a, 0, SEEK_SET);
lseek(fd_b, 0, SEEK_SET);
memset(buf_a, 0, sizeof(buf_a));
memset(buf_b, 0, sizeof(buf_b));
r_a = read(fd_a, buf_a, sizeof(buf_a));
r_b = read(fd_b, buf_b, sizeof(buf_b));
printf("after cross-write:\n");
printf(" A: %.*s\n", (int)r_a, buf_a);
printf(" B: %.*s\n", (int)r_b, buf_b);
close(fd_a);
close(fd_b);
unlink(path_a);
unlink(path_b);
return 0;
}
int main(int argc, char **argv)
{
char path_a[PATH_MAX];
char path_b[PATH_MAX];
const char *dir = argc >= 2 ? argv[1] : NULL;
make_path(path_a, sizeof(path_a), dir, "file_a.dat");
make_path(path_b, sizeof(path_b), dir, "file_b.dat");
int rc = test_two_files(path_a, path_b);
return report_result("test_two_files", rc);
}