c - 如何使用 stdio.h C 库读取文本文件并将内容写入另一个文本文件

标签 c file-io

我写了一个函数来读取一个文本文件并将内容写入另一个具有不同文件名的文本文件:

读取文件函数:

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);

他们成功地协同工作来读写文件。然而,在写入的文件中,在它的末尾,出现了一些奇怪的字符,如下所示:

ýýýý««««««««îþîþîþ

请帮我解决这个问题。当原始文件中不存在时,如何避免写入文件中出现最后的奇怪字符?

最佳答案

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.

关于c - 如何使用 stdio.h C 库读取文本文件并将内容写入另一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885731/

相关文章:

我们可以用阻塞套接字制作一个非阻塞服务器吗?

c - 运行循环 41881 次时出现段错误

python - 仅当在单独的文件中给出转换命令时,将 HTML 转换为 PDF 才有效

java - 将我想在 Eclipse 中使用的文本文件放在哪里?

java - 在 300 万个文本文件中搜索匹配项

c - C 中确定符号来源的工具

c - 将 char 指针类型转换为整数指针

c++ - 原生 CheckedListBox?

C11线程编程

android - 使用 Adob​​e Reader 在 Android 中打开 PDF