Skip to content

Instantly share code, notes, and snippets.

@kinichiro
Created February 26, 2018 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kinichiro/63d6262c5cdb3e0fe0bd5d0233a5ea03 to your computer and use it in GitHub Desktop.
Save kinichiro/63d6262c5cdb3e0fe0bd5d0233a5ea03 to your computer and use it in GitHub Desktop.
test program for pread and pwrite
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <fcntl.h>
#include <unistd.h>
#define FILENAME "pwrite_pread.dat"
void test_pwrite()
{
int fd;
char buf[10];
if((fd = open(FILENAME, O_RDWR|O_CREAT, 0660)) == -1)
err(1, "open");
if(write(fd, "987", 3) != 3)
err(1, "write");
if(pwrite(fd, "789", 3, 7) != 3)
err(1, "pwrite");
if(write(fd, "654", 3) != 3)
err(1, "write");
if(pwrite(fd, "456", 3, 4) != 3)
err(1, "pwrite");
if(write(fd, "3210", 4) != 4)
err(1, "write");
if(pwrite(fd, "0123", 4, 0) != 4)
err(1, "pwrite");
if(close(fd) == -1)
err(1, "close");
if((fd = open(FILENAME, O_RDONLY)) == -1)
err(1, "open");
if(read(fd, buf, 10) != 10)
err(1, "read");
if(strncmp(buf, "0123453210", 10) != 0)
err(1, "strncmp");
if(close(fd) == -1)
err(1, "close");
}
void test_pread()
{
int fd;
char buf[10];
if((fd = open(FILENAME, O_RDONLY)) == -1)
err(1, "open");
if(read(fd, buf, 3) != 3)
err(1, "read");
if(strncmp(buf, "012", 3) != 0)
err(1, "strncmp");
if(pread(fd, buf, 3, 7) != 3)
err(1, "pread");
if(strncmp(buf, "210", 3) != 0)
err(1, "strncmp");
if(read(fd, buf, 3) != 3)
err(1, "read");
if(strncmp(buf, "345", 3) != 0)
err(1, "strncmp");
if(pread(fd, buf, 3, 4) != 3)
err(1, "pread");
if(strncmp(buf, "453", 3) != 0)
err(1, "strncmp");
if(read(fd, buf, 4) != 4)
err(1, "read");
if(strncmp(buf, "3210", 4) != 0)
err(1, "strncmp");
if(pread(fd, buf, 4, 0) != 4)
err(1, "pread");
if(strncmp(buf, "0123", 4) != 0)
err(1, "strncmp");
if(read(fd, buf, 1) != 0)
err(1, "read");
if(close(fd) == -1)
err(1, "close");
}
int main(int argc, char *argv[])
{
test_pwrite();
test_pread();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment