MCPcopy Create free account
hub / github.com/XTXMarkets/ternfs / writeFile

Function writeFile

cpp/ktools/ternktools.cpp:39–125  ·  view source on GitHub ↗

Just a super dumb file test, to have a controlled environment where every syscall is accounted for.

Source from the content-addressed store, hash-verified

37// Just a super dumb file test, to have a controlled environment
38// where every syscall is accounted for.
39static void writeFile(int argc, const char** argv) {
40 ssize_t fileSize = -1;
41 ssize_t bufSize = -1; // if -1, all in one go
42 const char* filename = NULL;
43 bool closeAndReopen = false;
44 bool stat = false;
45
46 for (int i = 0; i < argc; i++) {
47 if (std::string(argv[i]) == "-buf-size") {
48 if (i+1 >= argc) { badUsage("No argument after -buf-size"); } i++;
49 bufSize = strtoull(argv[i], NULL, 0);
50 if (bufSize == ULLONG_MAX) {
51 badUsage("Bad -buf-size: %d (%s)", errno, strerror(errno));
52 }
53 } else if (std::string(argv[i]) == "-size") {
54 if (i+1 >= argc) { badUsage("No argument after -size"); } i++;
55 fileSize = strtoull(argv[i], NULL, 0);
56 if (fileSize == ULLONG_MAX) {
57 badUsage("Bad -size: %d (%s)", errno, strerror(errno));
58 }
59 } else if (std::string(argv[i]) == "-close-open") {
60 closeAndReopen = true;
61 } else if (std::string(argv[i]) == "-stat") {
62 stat = true;
63 } else {
64 if (filename != NULL) { badUsage("Filename already specified: %s", filename); }
65 filename = argv[i];
66 }
67 }
68
69 if (bufSize < 0) { bufSize = fileSize; }
70 if (fileSize < 0 || filename == NULL) { badUsage("No -size specified"); }
71
72 printf("writing %ld bytes with bufsize %ld to %s\n", fileSize, bufSize, filename);
73
74 int fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
75 if (fd < 0) {
76 die("could not open file %s: %d (%s)", filename, errno, strerror(errno));
77 }
78
79 if (closeAndReopen) {
80 if (close(fd) < 0) {
81 die("could not close file %s: %d (%s)", filename, errno, strerror(errno));
82 }
83 fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
84 if (fd < 0) {
85 die("could not reopen file %s: %d (%s)", filename, errno, strerror(errno));
86 }
87 }
88
89 uint8_t* buffer = (uint8_t*)malloc(bufSize);
90 if (buffer == NULL) {
91 die("could not allocate: %d (%s)", errno, strerror(errno));
92 }
93
94 uint64_t start = nanosNow();
95
96 ssize_t toWrite = fileSize;

Callers 1

mainFunction · 0.85

Calls 1

nanosNowFunction · 0.85

Tested by

no test coverage detected