- 论坛徽章:
- 1
|
- #include <sys/types.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <fcntl.h>
- #define BUFFER_SIZE 80
- #define READ_END 0
- #define WRITE_END 1
- int main(int argc, char* argv[])
- {
- /* argc must be 3 to ensure the correct usage */
- if (argc != 3) {
- printf("The usage of this program is:\n");
- printf("FileCopy input.txt copy.txt\n");
- return 1;
- }
- else {
- int pid;
- /* initialize the pipe and fork variables */
- int fd[2];/* argv[0] is the program name, argv[1] and argv[2] are the file names */
- char* infile = argv[1];
- char* outfile = argv[2];
- /* create a pipe */
- if (pipe(fd) == -1) {
- fprintf(stderr, "Pipe failed");
- return 1;
- }
- /* fork */
- pid = fork();
- /* if pid < 0 there is an error */
- if (pid < 0) {
- fprintf(stderr, "Fork error");
- return 1;
- }
- /* parent code */
- if (pid > 0) {
- FILE* in;
- int len;
- char buffer[BUFFER_SIZE];
- int i;
- /* close the unused end of the pipe */
- close(fd[READ_END]);
- /* make a buffer to store input file information */
- /* open input file */
- in = fopen(infile, "r");
- /* make sure it's not null */
- if (in == NULL) {
- fprintf(stderr, "Error opening file %s\n", infile);
- return 1;
- }
- /* read from the file into the pipe thru the buffer */
- while (1) {
- memset(buffer, 0, sizeof(buffer));
- len = fread(buffer, sizeof(char), BUFFER_SIZE, in);
- // printf("len 1=%d\n", len);
- if (len <= 0) {
- break;
- }
- for (i = 0; i < strlen(buffer); ++i) {
- printf("%c", buffer[i]);
- }
- write(fd[WRITE_END], buffer, len);
- }
- /* close the input file */
- fclose(in);
- close(fd[WRITE_END]);
- wait(NULL);
- }
- /* child process has pid == 0 */
- else {
- FILE* out;
- int len;
- /* create a buffer to read from the pipe and store into the out file */
- char buffer[BUFFER_SIZE];
- /* close the unused end of the pipe */
- close(fd[WRITE_END]);
- /* initialize the output file */
- /* w+ means open a file for writing and create it if it doesn't exist */
- out = fopen(outfile, "w");
- while (1) {
- memset(buffer, 0, sizeof(buffer));
- len = read(fd[READ_END], buffer, BUFFER_SIZE) ;
- if (len <= 0) {
- break;
- }
- fwrite(buffer, sizeof(char), len, out);
- }
- /* close the file and the pipe */
- fclose(out);
- close(fd[READ_END]);
- }
- }
- return 0;
- }
复制代码 我改成 fread + write 可以 , 但是下面這樣就不能, 是 fgets 跟 write 不能混用嗎?- /* read from the file into the pipe thru the buffer */
- while (fgets(buffer, BUFFER_SIZE, in)) {
- write(fd[WRITE_END], buffer, strlen(buffer)+1);
- buffer[0]='\0';
- }
复制代码- while(1) {
- if (read(fd[READ_END], buffer, BUFFER_SIZE) != 0)
- {
- fprintf(out,"%s",buffer);
- fflush(out);
- }
- else
- break;
- }
复制代码 |
|