gpt4 book ai didi

c - 为什么我无法关闭文件

转载 作者:行者123 更新时间:2023-11-30 21:10:18 24 4
gpt4 key购买 nike

关闭文件 fc 时遇到问题。这是我的代码

#include <stdio.h>
#include <wchar.h>
int main()
{
FILE* fc = fopen("template.txt","rt,ccs=UTF-8");
wchar_t subStr[2300];
fread(subStr,sizeof(wchar_t),2300,fc);
wchar_t* scrStr=new wchar_t[2300];
wcscpy(scrStr,subStr);
fclose(fc);
return 0;
}

最佳答案

该文件一开始可能没有正确打开。您必须检查 fopen 返回的流的“句柄”不是 NULL。以下代码检查文件“句柄”,并更改一些位以使其“合理”C。

#include <stdio.h>
#include <wchar.h>
int main()
{
wchar_t* scrStr = NULL;
FILE* fc = fopen("template.txt","rt,ccs=UNICODE");
// Check that the file was opened.
if(NULL != fc)
{
wchar_t subStr[2301];
size_t wcharsRead = fread(subStr, sizeof wchar_t , 2300, fc);
fclose(fc);
// Check if anything was read.
if(0 != wcharsRead)
{
// Terminate the string in the temporary buffer.
subStr[wcharsRead] = `\0`;
// Allocate a smaller string (use new, if you're in C++).
if(scrStr = malloc(1 + sizeof wchar_t * wcharsRead), NULL != scrStr)
{
// Copy the useful bit into the new string.
wcscpy(scrStr, subStr);
}
}
}
else
{
// Do some error handling
printf("Unable to open file. Error code: %d\r\n",errno);
}
// Check if a string was read.
if(NULL != scrStr)
{
// Do something with scrStr
// Free the string once it's finished with (use delete if you're in C++).
free(scrStr);
}
return 0;
}

关于c - 为什么我无法关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com