Issue
I'm trying to write byte by byte, 2 bytes, 4 bytes etc in chunks to a file. I currently have this code however am stuck.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc, char* argv[]){
char buf[1];
//creating output file
int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);
int infile = open(argv[2], O_RDONLY);
fread = read(infile, buf, 1);
printf("%s\n", buf);
write(outfile);
close(infile);
close(outfile)
}
Solution
First of all here I can't see where you had declared fread
variable,
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc, char* argv[]){
char buf[1];
//creating output file
int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);
int infile = open(argv[2], O_RDONLY);
fread = read(infile, buf, 1); // here fread var !!?
printf("%s\n", buf);
write(outfile);
close(infile);
close(outfile)
}
and this is not the way to write in a file, if you succeeded in compilation so according to this you will be able to write only one byte. You have to implement a loop either for
loop or while
loop in order to write all the byte from one file to another, if I am getting you correctly.
I am assuming here that you are trying to write data byte by byte from one file to another, So with that assumption here is the working code with some changes in your program..
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc, char* argv[]){
int fread =0;
char buf[1];
//creating output file
int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);
int infile = open(argv[2], O_RDONLY);
while(fread = read(infile, buf, 1)){ //change here number of bytes you want to read at a time and don't forget to change the buffer size too :)
printf("%s\n", buf);
write(outfile, buf, fread);
}
close(infile);
close(outfile)
}
Answered By - Jarvis__-_-__ Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.