Home > Back-end >  How to redirect a printf output to file?
How to redirect a printf output to file?

Time:01-10

I want to write the PID to a specific file. It echoes the pid in terminal so far. But how to write this PID to a file?

int main()
{
pid_t pid = getpid();
printf("%lu\n", pid);

char *filename = "/.wirebot/pid.txt";
char *home_dir = getenv("HOME");
char *filepath = malloc(strlen(home_dir)   strlen(filename)   1);
strncpy(filepath, home_dir, strlen(home_dir)   1);
strncat(filepath, filename, strlen(filename)   1);

FILE *fp;
fp = fopen(filepath, "w");
 if (fp == NULL) {
} else {
    fputs("%lu\n", pid, fp);
    fclose(fp);
    }

}

Too many arguments at fputs is the error I get.

CodePudding user response:

You should take a look at fprintf() function. Just remember to check(From you code i guess you are probably trying things with processes and then you will try it with forking), how to handle multiple processes writing to the same file.

CodePudding user response:

Here is a sample code to do that. You open a file and then use fprintf to write into it.

// C Program for the above approach  
#include<stdio.h>
int main()
{
    int i, n=2;
    char str[50];
   
    //open file sample.txt in write mode
    FILE *fptr = fopen("sample.txt", "w");
    if (fptr == NULL)
    {
        printf("Could not open file");
        return 0;
    }
   
    for (i = 0; i < n; i  )
    {
        puts("Enter a name");
        scanf("%[^\n]%*c", str);
        fprintf(fptr,"%d.%s\n", i, str);
    }
    fclose(fptr);
   
    return 0;
}
  •  Tags:  
  • c
  • Related