如果您已阅读所有文件,则必须保留,因为在第一时间读取的内容将...已阅读,而这不是您想要的。
注释后编辑代码:
#include
#include
#include
#include
#include
#include
#include
bool WriteLineFromFile(int dst, int src, bool *srcTerminated)
{
int lastChar = EOF;
char currentChar;
ssize_t nbCharRead;
ssize_t nbCharWrite;
do {
if ((nbCharRead = read(src, ¤tChar, 1)) < 0) {
fprintf(stderr, "%s : read(src, &buf, 1) : src=%d, errno='%s'.\n", __func__, src, strerror(errno));
return (false);
}
// End of file
if (nbCharRead == 0) {
(*srcTerminated) = true;
// Adding '\n' if necessary
if (lastChar != '\n' && lastChar != EOF) {
currentChar = '\n';
while ((nbCharWrite = write(dst, ¤tChar, 1)) != 1) {
if (nbCharWrite < 0) {
fprintf(stderr, "%s : write(dst, &buf, 1) : dst=%d, errno='%s'.\n", __func__, dst, strerror(errno));
return (false);
}
sleep(1);
}
}
return (true);
}
// Writing a char into the dst file
while ((nbCharWrite = write(dst, ¤tChar, 1)) != 1) {
if (nbCharWrite < 0) {
fprintf(stderr, "%s : write(dst, &buf, 1) : dst=%d, errno='%s'.\n", __func__, dst, strerror(errno));
return (false);
}
sleep(1);
}
lastChar = currentChar;
} while (currentChar != '\n');
return (true);
}
bool FileMerging(char *inputPathFile1, char *inputPathFile2, char *outputPathFile)
{
int inputFile1 = -1;
bool file1Terminated = false;
int inputFile2 = -1;
bool file2Terminated = false;
int outputFile = -1;
bool returnFunction = false;
// Openning all the file descriptor
if ((inputFile1 = open(inputPathFile1, O_RDONLY)) == -1) {
fprintf(stderr, "%s : open(inputPathFile1, O_RDONLY) : inputPathFile1='%s', errno='%s'.\n", __func__, inputPathFile1, strerror(errno));
goto END_FUNCTION;
}
if ((inputFile2 = open(inputPathFile2, O_RDONLY)) == -1) {
fprintf(stderr, "%s : open(inputPathFile2, O_RDONLY) : inputPathFile2='%s', errno='%s'.\n", __func__, inputPathFile2, strerror(errno));
goto END_FUNCTION;
}
if ((outputFile = open(outputPathFile, O_WRONLY | O_CREAT, 0644)) == -1) {
fprintf(stderr, "%s : open(outputPathFile, O_RDONLY) : outputPathFile='%s', errno='%s'.\n", __func__, outputPathFile, strerror(errno));
goto END_FUNCTION;
}
// Alternativly print a line from inputFile1 and inputFile2 to outputFile
do {
if (!file1Terminated) {
if (!WriteLineFromFile(outputFile, inputFile1, &file1Terminated)) {
goto END_FUNCTION;
}
}
if (!file2Terminated) {
if (!WriteLineFromFile(outputFile, inputFile2, &file2Terminated)) {
goto END_FUNCTION;
}
}
} while (!file1Terminated || !file2Terminated);
returnFunction = true;
/* GOTO */END_FUNCTION:
if (inputFile1 != -1) {
close(inputFile1);
}
if (inputFile2 != -1) {
close(inputFile2);
}
if (outputFile != -1) {
close(outputFile);
}
return (returnFunction);
}
int main(int argc, char *argv[])
{
if (argc != 4) {
fprintf(stderr, "This program wait 3 arguments on the command-line : inputFilePath1 inputPathFile2 outputPathFile.\n");
return (EXIT_FAILURE);
}
if (!FileMerging(argv[1], argv[2], argv[3])) {
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}