Arrays 使用malloced字符数组时无法创建文件
我通过下面的文章用标准C编写了一个PE文件查看器。它非常整洁,但我对第一行有一个问题:Arrays 使用malloced字符数组时无法创建文件,arrays,c,dynamic,malloc,Arrays,C,Dynamic,Malloc,我通过下面的文章用标准C编写了一个PE文件查看器。它非常整洁,但我对第一行有一个问题: #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
#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);
...
}
你知道我做错了什么吗?可能是我尝试混合不同数据类型或函数的方式
事先非常感谢
顺便说一句,如果你对我的C编码风格有什么建议,或者有些东西不是真正的“C标准”,请告诉我
如果有人有同样的问题。。。
尝试以管理员身份运行您的程序。。。这一切都与文件权限有关。除非有其他原因,否则无需复制
argv[1]
您可以直接使用它:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h> // use normal include guards
int main(int argc, char *argv[])
{
if (argc < 2){ // if the argument is not there the program would have undefined behavior
fprintf(stderr, "Usage: <prog> <filename>\n");
return EXIT_FAILURE;
}
HANDLE file = CreateFileA(argv[1], GENERIC_ALL, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
// ^^^^^^^
if (file == INVALID_HANDLE_VALUE) {
printf_s("Nope."); // Always throwing nopes.
}
//...
}
使用正确的数组大小,您仍然可以使用memcpy
或strcpy
库函数或其变体之一:
int length = strlen(argv[1]) + 1; // account for null byte
char *path = malloc(length); // sizeof char is always 1 byte
memcpy_s(path, length, argv[1], length); // path is already pointer, removing &
请注意,在代码中,filename
作为参数传递时,会衰减到指向其第一个元素的指针,因此您还应该删除&
或者简单地使用指针:
char *path = argv[1];
尽管指针选项基本上与直接使用argv[1]
相同,如第一段代码所示
如果存在与字符串无关的另一个问题,
GetLastError()
将帮助您确定问题所在。使该问题成为char*path=malloc(长度+1)终止空字符的代码>`仅使用argv[1]
有什么问题?例如,char*path=argv[1]代码>?或者干脆忘记路径。不管怎样,遵循适当的malloc,只需执行strcpy。另外,sizeof(char)
根据定义总是一个。如果你使用memcpy\u s()
是因为微软公司说memcpy()
被“弃用”,要知道你实际上被欺骗了memcpy()
从未也不会被任何人弃用,而且不会消失。MSVC敦促您使用C标准附录K中的标准功能,但Microsoft的实现是非标准和不可移植的。再见,谢谢你的建议;我将修复它们并继续:)我已经采用了这两种方法(直接使用argv[1]和完整的memcpy函数),但它仍然抛出“否”,就像它无法读取文件一样(file==无效的\u句柄\u值)…:(@JulioVargas,所有3个都应该可以,请尝试打印出GetLastError()
以查看确切的错误,并将其发布到此处。如果使用Unicode字符,您可能必须使用LPTSTR argv[]
和TCHAR
而不是char
。GetLastError()==5,这意味着这一切都与权限有关。我以管理员的身份运行该程序,一切正常。谢谢你的建议!@JulioVargas,的确,很高兴你解决了它,请注意,如果你认为它决定性地帮助你解决了问题,你可以。
#include <stdio.h>
#include <stdlib.h>
#include<string.h> // maybe needed for strdup
#include <Windows.h> // use normal include guards
int main(int argc, char *argv[]) {
if(argc < 2){ // if the argument is not there the program would have undefined behavior
fprintf(stderr, "Usage: <prog> <filename>\n");
return EXIT_FAILURE;
}
// allocates memory for the new string and duplicates it
char* path = _strdup(argv[1]); // MSVC can complain about POSIX strdup()
//...
// you'll need to free path
}
int length = strlen(argv[1]) + 1; // account for null byte
char *path = malloc(length); // sizeof char is always 1 byte
memcpy_s(path, length, argv[1], length); // path is already pointer, removing &
char *path = argv[1];