在使用C的Linux下,如何將整個環境寫入文件?代碼不能覆蓋文件中已有的數據?以下程序的結果只是將一行內容寫入文件中。在使用C的Linux中,如何將整個環境寫入文件?
我該如何解決這個問題?
#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;
}
這不是python。 –
如果您不想覆蓋文件中已有的數據,您可能需要在開始寫入之前尋求結束,或者您需要在flags中使用'O_APPEND'來打開()'。 'O_APPEND'的作用更好,因爲它總是追加,即使另一個進程(或文件描述符)也寫入同一文件,而seek選項不處理這些情況。 –
你應該檢查是否可以使用POSIX ['dprintf()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/dprintf.html) 。另外,根據情況,您不需要使用'',而且對於現代的POSIX,您通常不需要'()'(特別是您不需要它)。 –