Skip to content

Instantly share code, notes, and snippets.

@keichi
Created April 14, 2023 08:00
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 keichi/8e81f8174d52fbce474506412a0be0f9 to your computer and use it in GitHub Desktop.
Save keichi/8e81f8174d52fbce474506412a0be0f9 to your computer and use it in GitHub Desktop.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <vector>
struct header {
int n;
};
int main()
{
int fd = open("foo.dat", O_RDONLY, 0644);
if (fd == -1) {
perror("Failed to open file");
return -1;
}
struct header h;
read(fd, &h, sizeof(h));
std::vector<double> buf(h.n);
char *ptr = reinterpret_cast<char *>(buf.data());
ssize_t bytes_remaining = h.n * sizeof(double);
while (bytes_remaining > 0) {
ssize_t bytes_read = read(fd, ptr, bytes_remaining);
ptr += bytes_read;
bytes_remaining -= bytes_read;
}
for (int i = 0; i < h.n; i++) {
std::cout << buf[i] << std::endl;
}
close(fd);
return 0;
}
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <vector>
struct header {
int n;
};
int main()
{
size_t N = 1000;
std::vector<double> buf(N);
for (size_t i = 0; i < N; i++) {
buf[i] = i;
}
int fd = open("foo.dat", O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
perror("Failed to open file");
return -1;
}
struct header h;
h.n = N;
write(fd, &h, sizeof(h));
char *ptr = reinterpret_cast<char *>(buf.data());
ssize_t bytes_remaining = h.n * sizeof(double);
while (bytes_remaining > 0) {
ssize_t bytes_written = write(fd, ptr, bytes_remaining);
ptr += bytes_written;
bytes_remaining -= bytes_written;
}
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment