MCPcopy Create free account
hub / github.com/Pagghiu/SaneCppLibraries / read

Method read

Libraries/FileSystem/FileSystem.cpp:348–422  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

346}
347
348SC::Result SC::FileSystem::read(StringSpan path, IGrowableBuffer&& buffer)
349{
350 StringSpan encodedPath;
351 SC_TRY(convert(path, fileFormatBuffer1, fileTransportBuffer1, &encodedPath));
352#if SC_PLATFORM_WINDOWS
353 HANDLE hFile = ::CreateFileW(encodedPath.getNullTerminatedNative(), GENERIC_READ, FILE_SHARE_READ, nullptr,
354 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
355 if (hFile == INVALID_HANDLE_VALUE)
356 {
357 return formatError(GetLastError(), path, true);
358 }
359 auto deferClose = MakeDeferred([&]() { ::CloseHandle(hFile); });
360
361 // Get file size
362 LARGE_INTEGER fileSize;
363 if (!::GetFileSizeEx(hFile, &fileSize))
364 {
365 return formatError(GetLastError(), path, true);
366 }
367
368 // Grow buffer to accommodate the file
369 if (!buffer.resizeWithoutInitializing(static_cast<size_t>(fileSize.QuadPart)))
370 {
371 return Result::Error("Failed to grow buffer");
372 }
373
374 // Read the file
375 DWORD bytesRead;
376 if (!::ReadFile(hFile, buffer.data(), static_cast<DWORD>(fileSize.QuadPart), &bytesRead, nullptr))
377 {
378 return formatError(GetLastError(), path, true);
379 }
380
381 if (bytesRead != static_cast<DWORD>(fileSize.QuadPart))
382 {
383 return Result::Error("Read incomplete");
384 }
385
386 return Result(true);
387#else
388 int fd = ::open(encodedPath.getNullTerminatedNative(), O_RDONLY);
389 if (fd == -1)
390 {
391 return formatError(errno, path, false);
392 }
393 auto deferClose = MakeDeferred([&]() { ::close(fd); });
394
395 // Get file size
396 struct stat fileStat;
397 if (::fstat(fd, &fileStat) == -1)
398 {
399 return formatError(errno, path, false);
400 }
401
402 // Grow buffer to accommodate the file
403 if (!buffer.resizeWithoutInitializing(static_cast<size_t>(fileStat.st_size)))
404 {
405 return Result::Error("Failed to grow buffer");

Callers

nothing calls this directly

Calls 7

MakeDeferredFunction · 0.85
closeFunction · 0.85
readFunction · 0.85
ErrorEnum · 0.50
ResultClass · 0.50
dataMethod · 0.45

Tested by

no test coverage detected