c - 添加/附加文本到文件中的行末尾

标签 c

所以我尝试将文本添加到行尾。现在它把它很好地添加到开头,但我不知道如何将它添加到结尾。

因此,此处的代码从一个文件中获取内容,并将其添加到临时文件中,然后将其与添加的文本一起写回原始文件。然而现在它在行的开头添加文本,我需要它在每行的末尾。

我还想知道是否有一种方法可以将文本附加到每行的末尾,而不将所有内容复制到临时文件,然后将输出显示到标准输出?

int add_text_end(FILE *fileContents) 
{

    FILE *tmp = tmpfile();
    char *p;
    FILE *fp;
    char line[LINESIZE]; 

    if ((fileContents = fopen("fileContents.txt", "r")) == 0) 
    {
        perror("fopen");
        return 1; 
    }
    /* Puts contents of file into temp file */
    fp = fopen("fileContents.txt", "r");
    while((p = fgets(line, LINESIZE, fp)) != NULL)
    {
        fputs(line, tmp);
    }
    fclose(fp); 

    rewind(tmp);
    /* Reopen file to write to it */
    fopen("fileContents.txt", "w");
    while ((p = fgets(line, LINESIZE, tmp)) != NULL)
    {
        line[strlen(line)-1] = '\0';  /* Clears away  new line*/
        sprintf(line, "%s %s", line, "test");
        fputs(line, fp);
    }
    fclose(fp); 
    fclose(tmp);
    return 0;

}

最佳答案

有一个更好的方法来做到这一点,而不会以错误的方式使用 sprintf 导致未定义的行为(你不能让目标缓冲区与 sprintf 作为参数读取的缓冲区相同) - 将 while block 更改为以下:

while ((p = fgets(line, LINESIZE, tmp)) != NULL)
{
        line[strlen(line)-1] = '\0';  /* Clears away  new line*/
        fprintf(fp, "%s %s\n", line, "test");
}

如果文件有 \r\n结尾,然后用这个代替:

while ((p = fgets(line, LINESIZE, tmp)) != NULL)
{
        char *r;
        if ((r = strchr(line, '\r')) != NULL)
            *r = '\0';  /* Clears carriage return */
        fprintf(fp, "%s %s\r\n", line, "test");
}

确保#include <string.h>如果您收到有关 strchr() 的警告没有被宣布。

关于c - 添加/附加文本到文件中的行末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31083536/

相关文章:

c - 为什么 strcat() 缺少一些连接字符串?

c++ - 如何从 C++ 应用程序在 os x 上打开 xterm?

c - 仅在一个函数中出现 "variable_name"未声明错误

我可以附加到预处理器宏吗?

c - LLVM中的指针分析

在C中使用fork创建n个后台进程

c++ - extern "C"函数访问代码

c++ - GCC:空程序 == 23202 字节?

c - 释放 2 个具有相同地址的指针

c - Makefile 无法为简单项目创建单独的对象文件夹