I am coding a PE file viewer in standard C by following this article. It is pretty neat, but I have a problem with the first lines:
#include "stdafx.h"
#include "Windows.h"
#include <iostream>
int main(int argc, char* argv[]) {
const int MAX_FILEPATH = 255;
char fileName[MAX_FILEPATH] = {0};
memcpy_s(&fileName, MAX_FILEPATH, argv[1], MAX_FILEPATH);
...
}
As you can see, the author is defining the MAX_FILEPATH as 255, but I cannot do the same because the input argument I will give may be larger than that.
I decided to do dynamic memory allocation with malloc, so I can have an auto-sized array (the exact argument's length) and also, to save me the 'memcpy_s' function:
#include <stdio.h>
#include "Windows.h"
#pragma warning (disable: 6011 6386 6387) // MSVC is giving me a headache.
int main(int argc, char *argv[]) {
int length = strlen(argv[1]); // Yes, I only care for 1 input argument.
char* path = malloc(length * sizeof(char));
int i = 0;
for (; i <= length; i++) {
if (i < length) {
path[i] = argv[1][i];
}
else {
path[i] = '\0';
}
}
...
}
I know that the 'for cicle' is probably not the best option in terms of speed, but I am not worried about it, yet. Instead, I am worried because everything seems to be fine, but when I reach the second part of the code (which is the creation of the HANDLE), it is always returning error.
HANDLE file = CreateFileA(path, GENERIC_ALL, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE) {
printf_s("Nope."); // Always throwing nopes.
}
Do you have an idea of what am I doing wrong? Maybe the way I am trying to mix up different data types or functions...?
Thank you very much, in advance.
By the way, if you have suggestions about my C coding style, or if something is not really 'C standard', please, let me know.
IF SOMEONE IS HAVING THE SAME PROBLEM...
Try to run your program as Admin... it is all about file permissions.
char* path = malloc(length+1);for the terminating null character. `argv[1]? E.g.char *path= argv[1];? Or just forget aboutpathat all.mallocjust dostrcpy.sizeof(char)is always one by definition. And if you're usingmemcpy_s()because MSVC saidmemcpy()was "deprecated", be aware you were effectively lied to.memcpy()hasn't been and won't be deprecated by anyone - it's standard C and it's not going away. MSVC pushes you to use the*_sfunctions that would be standard per Annex K of the C standard, but Microsoft's implementation is non-standard and non-portable. See open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm#impementations