1

I have the following simple program that catenates infile to outfile

  char *execArgs[] = { "cat", NULL};
  int outfile = open("outfile", O_WRONLY | O_CREAT, 0644);
  int infile = open("infile", O_RDONLY, 0);
  dup2(outfile, STDOUT_FILENO); 
  dup2(infile, STDIN_FILENO); 
  close(outfile);
  close(infile);
  execvp(execArgs[0], execArgs);

Now, suppose the content of infile is

this is infile

and outfile is

this is outfile

After running the program, the content of outfile has an extra "e" at the end as such

this is infilee

Also, if the outfile is instead

this is outfile
this is outfile

It becomes

this is infilee
this is outfile

What is wrong?

Mariska
  • 1,913
  • 5
  • 26
  • 43
  • int outfile = open("outfile", O_WRONLY | O_CREAT, 0644); this line causes the problem, you want to only create if the outfile does not already exist. – user3629249 Oct 19 '14 at 01:09

3 Answers3

1

What you're experiencing is the expected behavior. cat just writes the number of bytes it reads, so since the original outfile is longer, the remaining bytes contain what they contained before.

If you're asking why you get different behavior from using the shell to perform:

cat < infile > outfile

the reason is that the shell opens outfile (or any target of >) with O_TRUNC, which truncates the file to zero length as part of opening it. You can get the same behavior by adding | O_TRUNC to your open call's flags argument.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

Try using O_TRUNC this will truncate the file it it exists.

int outfile = open("outfile", O_WRONLY | O_CREAT | O_TRUNC, 0644);
Musa
  • 96,336
  • 17
  • 118
  • 137
0

It doesn't have an extra e, it has the same e it always had at that position.

Look at the strings you're writing:

this is infilee
this is outfile
              ^
              +-- lines up

The problem is that the output is not truncated, and thus it retains all its old content. You're just overwriting it from the start.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825