I have been looking online for hours but I guess don't know what search terms to use while trying to solve my problem. "Write" has too many connotations and I can't narrow it down. I could use help with the title of this question.
I'm writing a bunch of garbage characters after I finish writing the file, and that's not what I want of course. How do I terminate once my file is done being read?
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
using std::cerr;
using std::endl;
const int BUFF_SIZE = 4096;
int main (int argc, char* argv[]) {
if (argc < 2) {
cerr << "Usage:\t./cat FILE ..." << endl;
return EXIT_FAILURE;
} // if
for (int i = 1; i < argc; ++i) {
int fd;
if ((fd = open(argv[i], O_RDONLY)) == -1) {
perror(argv[i]);
return EXIT_FAILURE;
} // if
char buf [BUFF_SIZE];
int r;
while ((r = read(fd, buf, BUFF_SIZE-1)) > 0) {
buf[BUFF_SIZE-1] = '\0';
if ((write(STDOUT_FILENO, buf, BUFF_SIZE)) == -1) { // the offending line
perror(argv[i]);
return EXIT_FAILURE;
} // if
} // while
if (r < 0) {
perror(argv[i]);
return EXIT_FAILURE;
} // if
if (close(fd) == -1) {
perror(argv[i]);
return EXIT_FAILURE;
} // if
} // for
} // main
Aucun commentaire:
Enregistrer un commentaire