Unable to write files on Windows

点点圈 提交于 2019-12-24 04:46:05

问题


I am trying to save some files using C, with this code:

sprintf(playerinput,"%s",end);
sprintf(fileloc,"%s/.notend",getenv("HOME"));
playerdata = fopen(fileloc, "w+"); /*create the new file*/
if (!playerdata)
{
printf("\n\t\t\tCould not save settings file.");    
return;
} else {
fputs(playerinput,playerdata); 
fclose(playerdata); 
}

It should set playerinput to the end variable, which works on Linux, then set the file location to the homearea/.notend, then make or edit the file, and put it out. In Linux (gcc), this works fine. The same code, however, on Windows (i586-mingw32msvc-gcc, does not work. Am I doing something wrong, or is another header file needed? Currently I have:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>   
#include <string.h>
#include <stdlib.h>
#define MAX_NOTES 200
#define MAX_NAMES_TEXT 200
#define MAX_NOTES_TEXT 2000

as my headers and defines. If you need more information, just ask.


回答1:


The environment variable HOME is not a default environment variable on Windows so:

getenv("HOME");

will return NULL. You need to use a different function to obtain a user's home directory on Windows, SHGetFolderPath will provide this:

char path[MAX_PATH + 1] = "";

if (SUCCEEDED(SHGetFolderPath(0, 
                              CSIDL_LOCAL_APPDATA,
                              0,
                              SHGFP_TYPE_CURRENT,
                              path)))
{
    std::cout << path << "\n";
}

This output:

C:\Documents and Settings\admin\Local Settings\Application Data

on my machine.




回答2:


To which location are you trying to write your file? Does the application have the right permissions to write to that location?

EDIT: Looking at the path style you just defined C://Documents and Settings//..., you should try it with C:\\\\Documents and Settings\\.... Note that there's double backslash for each slash in the path. I'm not sure if fopen() would convert / to \, so it's worth a try.

If you're sure that this would be running on Windows Vista and above you can get this path using getenv("HOMEPATH"). I would suggest a macro definition like:

#ifdef _WIN32
#    define HOME_ENV "HOMEPATH"
#else
#    define HOME_ENV "HOME"
#endif

followed by: getenv(HOME_ENV) to get the home directory for the user.



来源:https://stackoverflow.com/questions/9706084/unable-to-write-files-on-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!