【发布时间】:2017-12-21 23:00:19
【问题描述】:
我正在使用 Win32 API 开发一个客户端-服务器应用程序,并且我正在尝试从 login.txt 文件中删除一条记录,该文件存储了我所有登录的用户。问题是我正在使用的文件没有被删除,临时文件没有被重命名(他们做了 2-3 次,但在几次注销后它失败了)。
我的代码是:
EnterCriticalSection(&CriticalSection2);
TCHAR tmpString[256];
FILE *tmp = NULL;
tmp = fopen("C:\\Users\\Liviu\\Desktop\\temporaryFile.txt", "w");
if (!tmp)
{
printf("Temporary file could not open");
system("pause");
return;
}
TCHAR searchString[20];
// Removes the possibility of having the ThreadId = password
sprintf(searchString, "%s%d", ",", GetCurrentThreadId());
// Paste all the lines execept the specified record to the tmp file
while (fgets(tmpString, 255, loginFile))
{
if (!strstr(tmpString, searchString))
{
fputs(tmpString, tmp);
}
}
fclose(tmp);
fclose(loginFile);
// I have put "while" here just to make sure this actually works, but it doesn't
while (remove("C:\\Users\\Liviu\\Desktop\\login.txt") != 0)
;
while (rename("C:\\Users\\Liviu\\Desktop\\temporaryFile.txt", "C:\\Users\\Liviu\\Desktop\\login.txt") != 0)
;
LeaveCriticalSection(&CriticalSection2);
我怎样才能做到这一点?我认为是关于线程同步的,但我不知道如何修复它。
【问题讨论】:
-
"C:\..\..\in.txt"是驱动器 c: 根目录上方的两个目录,这看起来不对。 -
什么是
GetLastError()? -
想知道这是否很简单,例如使用 unicode 文本构建项目,但对 CreateFile() 使用 ansi 文本调用。
-
您也一直使用不同的选项 -
OPEN_EXISTING、CREATE_NEW、CREATE_ALWAYS。可能是 \??\c:\in.txt 根本不存在 -
为什么不改用
CopyFile()?