char *file_open(const char *name) { HANDLE handle = CreateFileA(name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if(handle != INVALID_HANDLE_VALUE) { DWORD size = GetFileSize(handle, NULL); if(size != INVALID_FILE_SIZE) { // Allocate an extra byte to make sure there's at least one null at // the end of the file char *buffer = VirtualAlloc(NULL, ++size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if(buffer) { DWORD read; if(ReadFile(handle, buffer, size, &read, NULL) && read < size) { CloseHandle(handle); return buffer; } VirtualFree(buffer, 0, MEM_RELEASE); } } CloseHandle(handle); } err_format("Cannot open file '%s'", name); return NULL; }
static void read_header(header *hdr) { char *buffer = 0; size_t buflen = 0; if (getline(&buffer, &buflen, stdin) == -1) err_error("Failed to read header line"); int offset = 0; if (sscanf(buffer + offset, "%31s%n", hdr->r_name, &offset) != 1) err_format("header row name", buffer); for (int i = 0; i < MAX_VALUES; i++) { int extra; if (sscanf(buffer + offset, "%31s%n", hdr->c_name[i], &extra) != 1) err_format("header column name", buffer); assert(extra > 0); offset += extra; } free(buffer); }
static size_t read_samples(size_t max_rows, sample *data) { char *buffer = 0; size_t buflen = 0; size_t numrow = 0; while (getline(&buffer, &buflen, stdin) != -1 && numrow < max_rows) { int offset; if (sscanf(buffer, " %31s%n", data[numrow].r_name, &offset) != 1) err_format("row name", buffer); for (int i = 0; i < MAX_VALUES; i++) { int extra; if (sscanf(buffer + offset, "%lf%n", &data[numrow].value[i], &extra) != 1) err_format("value", buffer); assert(extra > 0); offset += extra; } numrow++; } free(buffer); return numrow; }