在Linux中使用C,如何将整个环境写入文件?

In Linux using C, how to write the entire environment to a file?

在Linux中使用C,如何将整个环境写入一个文件?代码不能覆盖文件中已有的数据?以下程序的结果是文件中只写入了一行内容。

我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

extern char** environ;

int main(int argc, char *argv[])
{
    int ff;
    char buffer[100];
    ff = open("file.txt", O_CREAT | O_WRONLY, 0600);
    if (ff == -1)
    {
        printf("Fail to create and open file.\n");
        exit(1);
    }
    char **tmp = environ;
    while (*tmp != NULL){
        // printf("\n%s\n", *tmp);
        write(ff, ("\n%s\n", *tmp), 100);
        tmp++;
    }
    close(ff);
    return 0;
}

这就是问题所在

write(ff, ("\n%s\n", *tmp), 100);

,运算符丢弃左边的所有操作数,留下最后一个操作数,*tmp这意味着没有换行符被写入。

此外,此行调用未定义的行为,因为您不知道 *tmp 是否指向 100 字节缓冲区,硬编码 100 是错误的。

你需要这样的东西

char **tmp;
tmp = environ;
for (int i = 0 ; tmp[i] != NULL ; ++i)
{
    char newline;
    newline = '\n';

    write(ff, tmp[i], strlen(tmp[i]));
    write(ff, &newline, 1);        
}

你也应该试试这个

dprintf(ff, "%s\n", temp[i]);

Linux.

可用