Home > Blockchain >  Mapping output file C (windows)
Mapping output file C (windows)

Time:12-14

I have a problem with mapping a .txt file to memory that doesn't have any inserted data yet, but I keep getting error 1006 when calling the CreateFileMapping function. I have already resolved the mapping to memory for Linux and now I wanted to convert it to Windows, but I can't figure it out.

This is the code for Linux:

// Open the output file
int output_file = open(argv[2], O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (!output_file) {
  printf("Unable to create file.");
  exit(1);
}

// Get the size of the output file
size_t output_file_size = strlen(input_data_without_comments);

// Set length to file
ftruncate(output_file, output_file_size);

// Map the output file into memory
char *output_data = mmap(NULL, output_file_size, PROT_WRITE, MAP_SHARED, output_file, 
0);
if (output_data == MAP_FAILED) {
  printf("Error: failed to map output file\n");
  exit(1);
}

This is code for windows that I have:

// Open the output file
printf("Open the output file\n"); 
HANDLE output_file = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 
NULL, CREATE_ALWAYS, 0, NULL);
if (output_file == INVALID_HANDLE_VALUE) {
  _tprintf(_T("Error: could not open output file '%s'\n"), argv[2]);
  exit(1);
}

// Initializing variables for output length
DWORD output_file_size = 0;
DWORD high_output_file_size = 0;

// Get length of the output file
output_file_size = GetFileSize(output_file, &high_output_file_size);
printf("Size of the output_file: %d\n", output_file_size);

// Output file mapping
printf("Output file mapping\n"); 
HANDLE output_file_mapping = CreateFileMapping(output_file, NULL, PAGE_READWRITE, 0, 0, 
NULL);
if (output_file_mapping == NULL) {
  _tprintf(_T("Unable to create file mapping (output_file)\n"));
  _tprintf(_T("Last error was: %i"), GetLastError());
  exit(1);
}

// Set length to file
printf("Set length to file\n");
SetFilePointer(output_file, output_file_size, NULL, FILE_BEGIN);
SetEndOfFile(output_file);

// Map the output file into memory
printf("Map the output file into memory\n");
char *output_data = MapViewOfFile(output_file_mapping, FILE_MAP_WRITE, 0, 0, 
output_file_size);
if (output_data == NULL) {
  printf("Error: failed to map output file\n");
  exit(1);
}

CodePudding user response:

The error 1006 is ERROR_FILE_INVALID (the Microsoft error code reference is very useful).

Searching for ERROR_FILE_INVALID in the CreateFileMapping documentation gives:

An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should test for files with a length of 0 (zero) and reject those files.

You can't create a mapping of an empty file. You need to set the size before you create the mapping, not after.

  • Related