0
我在完成寫入文件後正在編寫一堆垃圾字符,這當然不是我想要的。我的文件完成讀取後如何終止?寫完(2)在完成寫入文件後編寫一堆垃圾字符
#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
read()返回什麼?什麼是r?你應該如何處理這些信息(關於buf)?這應該如何影響你的寫作() –