Search code examples
cfiledup2

dup2 not switching to file?


I'm trying to learn dup2 and switch the stdout to a file rather than terminal. This is the example that works everywhere but not sure why it is not working for me. I don't think I need a fork() because I don't need a different process for execute just the print statement in file.

Where function is called:

int main(int argc, char **argv){
  char *something = "hello";
  saveHistoryToFile(something);
}

//This is the function. There is a file names history .txt

void saveHistoryToFile(char *history){
  int fw = open("history.txt",O_WRONLY | O_APPEND);
  dup2(fw, 1);
  printf("%s", history);
}

THE ERROR: it prints into terminal not file!


Solution

  • Your code with error checking:

    #include <stdio.h>
    #include <unistd.h>
    #include <fcntl.h>
    
    int saveHistoryToFile(char *history);
    
    int main(int argc, char **argv){
      char *something = "hello";
      if(0>saveHistoryToFile(something)) return 1;
      if(0>fclose(stdout)) return perror("fclose"),-1;
    }
    
    int saveHistoryToFile(char *history){
      int fw = open("history.txt",O_WRONLY | O_APPEND /*|O_CREAT, 0640*/ );
      if (0>fw) return perror("open"),-1;
      if (0>dup2(fw, 1)) return perror("dup2"),-1;
      if (0>(printf("%s", history)))  return perror("printf"),-1;
    }
    

    On a first run, I get "open: No such file or directory" because I do not have "history.txt" in my current directory.

    If I add it or uncomment the O_CREAT, 0640, it runs fine on my machine.

    Of course, you might run into other problems (e.g, EPERM) but the perrors should give you a hint.