post  copying data from file to anothr file

CD4 (27)   Link to this post
hello i am a newbie.. i had been following Beginning linux programming 4th edition. I tried to go for a sample but the data isnt getting copied to other file but the new file files.in is formed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/types.h> 
#include<stdio.h>

int main() {
char buff[]="Hello world! This is CodeZer0.I love using linux specially BackTrack4.I am concentrating on c programming\n";
char block[10];
int op,in;
int rdbyte;
 op=open("files.out1",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
 write(op,buff,sizeof(buff));
  if (op==-1)
   write(1,"some error\n",11);
 in=open("files.in",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
  if (in==-1)
   write(1,"some error in files.in\n",23);
 while((rdbyte=read(op,block,sizeof(block)))>0);
 write(in,block,rdbyte);
return 0;
}

please help..thanks in advance
Duoas (2964)   Link to this post
Line 19 has a stray semicolon.
CD4 (27)   Link to this post
well thanks for pointing out (;) mistake but still files.in is empty.the data from files.out1 hasn't been copied to it.please help
Duoas (2964)   Link to this post
It is because your file handling is scrambled.

Line 12: you open a file for writing
Line 13: you write some stuff to it
Line 14: you check to see whether the file opened properly (non sequitur)

Line 19: you try to read stuff from the output file (that you just created and left the file pointer at the end of it)


Try putting a lseek(op,0,SEEK_SET); before line 19 and see what that does.
You might also want to swap lines 13 and 14.

Hope this helps.
Last edited on
CD4 (27)   Link to this post
hello duoas.. i am a coplete newbie so its not getting clear.. i re-wrote the program with many changes where the eror was taking place.. can you explain abit more on wats the problem..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/types.h> 
#include<stdio.h>

int main() {
char block[106];
int op,in;
int rdbyte;
 op=open("files.out1",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR|S_IXUSR|S_IROTH|S_IWOTH|S_IXOTH);
   if (op==-1)
   write(1,"some error\n",11);
 rdbyte=write(op,"Hello world! This is CodeZer0.I love using linux specially BackTrack4.I am concentrating on c programming\n",106);
 if (rdbyte==0)
  write(1,"data not written\n",17);

 in=open("files.in",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR|S_IXUSR|S_IROTH|S_IWOTH|S_IXOTH);
  if (in==-1)
   write(1,"some error in files.in\n",23);
 printf("%d\n",op);
 rdbyte=read(op,block,106);
 if (rdbyte==0)
  write(1,"data not read\n",14);
 if (rdbyte==-1)
  write(1,"some error\n",11);
 rdbyte=write(in,block,106);
 if  (rdbyte==0);
  write(1,"data not entered\n",17);
 if (rdbyte==-1)
  write(1,"some error2\n",15);

return 0;
}


shell output::
# ./cp
3
data not read
data not entered

Registered users can post in this forum.