我编写了如下函数来读取文本文件并将内容写入另一个具有不同文件名的文本文件:
读取文件功能:
char *getFileContent (const char *fileName)
{
char errorBuffer[50];
//Prepare read file
FILE *pReadFile;
long bufferReadSize;
char *bufferReadFile; //This variable is going to be returned as file content
size_t readFileSize;
pReadFile = fopen (fileName, "rb");
if (pReadFile != NULL)
{
// Get file size.
fseek (pReadFile , 0 , SEEK_END);
bufferReadSize = ftell (pReadFile);
rewind (pReadFile);
// Allocate RAM to contain the whole file:
bufferReadFile = (char*) malloc (sizeof(char) * bufferReadSize);
if (bufferReadFile != NULL)
{
// Copy the file into the buffer:
readFileSize = fread (bufferReadFile, sizeof(char), bufferReadSize, pReadFile);
if (readFileSize == bufferReadSize)
{
return bufferReadFile;
fclose (pReadFile);
free (bufferReadFile);
} else {
//fread failed
sprintf (errorBuffer, "File reading failed for file:\n%s", fileName);
MessageBox (NULL, errorBuffer, "Error file reading", MB_ICONERROR | MB_OK);
}
} else {
//malloc failed
sprintf (errorBuffer, "Memory allocation failed for file:\n%s", fileName);
MessageBox (NULL, errorBuffer, "Error memory allocation", MB_ICONERROR | MB_OK);
}
} else {
//fopen failed
sprintf (errorBuffer, "File opening failed for file:\n%s", fileName);
MessageBox (NULL, errorBuffer, "Error file opening", MB_ICONERROR | MB_OK);
}
}
写入文件代码:
//Get file content from read file
char *fileContent = getFileContent (readFileName);
FILE *pWriteFile = fopen (writeFileName, "wb");
fwrite (fileContent, sizeof (char), strlen (fileContent), pWriteFile);
fclose (pWriteFile);
他们一起成功地读写文件。但是,在写入的文件中,在它的末尾,一些奇怪的字符是这样出来的:
ýýýý««««««««îþîþîþ
请帮我解决这个问题。当原始文件中不存在时,如何避免写入文件中的最终奇怪字符?