我有一个简单的问题让我整天发疯。我试图在不知道当前用户名的情况下打开当前用户桌面上的文件。
这个想法是我将使用对 API 的 GetCurrentUser 调用来获取用户名。然后格式化一个字符串以给出完整路径目录,并将该变量传递给 fopen 以打开文件。这是我正在处理的代码,我没有收到编译器错误,它编译得很好,但没有写入文件。
int main() {
char pathName[200]; // declaring arrays
char userName[100];
DWORD userNameSize = sizeof(userName); // storage for user name
if (!GetUserName(userName, &userNameSize)) { cout << "user not found"; }
else { cout "hello" << userName;} // error checking
// format for Windows 7 desktop
sprintf(pathName, "\"C:\\Users\\%s\\Desktop\\text.txt\"", userName);
cout << pathName << "\n"; // confirms correct location
const char* fileLocation = pathName; // pointer to full path to pass into fputs
const char* test = "test"; // test information to write to file to confirm
FILE *f = fopen(fileLocation,"a+"); // open file in append mode
fputs(test, f); // write to file
fclose(f); // flush and exit
return 0;
}
也许我需要使用不同的调用来格式化字符串?或者将 fileLocation 声明为不同的变量类型?
我对 C++ 相当陌生,如果有任何提示可以帮助我能够在当前用户的桌面上打开文件,我将不胜感激。谢谢。
针对 JERRY 的建议进行编辑:
这就是我最近的评论所指的:
#include <iostream>
#include <cstring>
#include <string>
#include <conio.h>
using namespace std;
string location ("C:\\Users\\testuser\\Desktop\\log.dat");
char cstr = char* [location.size()]; //This is a problematic line
strcpy (cstr, location.c_str());
void write(const char* c)
{
const char* fileLocation = cstr;
//const char* fileLocation = g_pathName;
FILE *f = fopen(fileLocation,"a+"); // This is the problematic line right here.
if(f!=NULL)
{
fputs(c,f); // append to end of file
fclose(f); // save so no entries are lost without being flushed
}
}
int main ()
{
write("test");
cout << "done";
_getch();
return 0;
}