我编写了如下函数来读取文本文件并将内容写入另一个具有不同文件名的文本文件中:
读取文件功能:
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);
他们成功地一起工作来读写文件。但是,在书面文件中,最后会出现一些奇怪的字符:
YYYY««««««««îþîþîþ
请帮我解决这个问题。如果原始文件中没有写入文件中的最终奇怪字符,我怎么能避免它?
答案 0 :(得分:3)
fwrite (fileContent, sizeof (char), strlen (fileContent), pWriteFile);
strlen
()在这里不起作用,因为fileContent包含二进制数据。二进制数据可能包含一个空字节,这意味着strlen
()太短,或者它可能不包含空字节,这意味着strlen
()将读取超过fileContent
,直到它找到一个空字节。这就是你最后看到垃圾的原因。
另请注意,在您的读取例程中,fclose
()和free
()永远不会发生,因为它们位于return
语句之后。但是,请注意,在您编写数据之前,不能free
()数据。
另一方面,如果它不是二进制文件,您只需要在数据末尾终止0,然后strlen()就可以了。因此,在您的读取中,您需要分配另一个字节并确保该字节为零:
bufferReadFile = (char*) malloc (sizeof(char) * bufferReadSize + 1); // note the + 1
bufferReadFile[bufferReadSize] = 0; // the terminating null byte.