2012-03-08 46 views
0

您好我最近被賦予了任務C.側身拼接

任務的目的是從兩個文本文件和輸出的每個文件邊的每一行並排在中間的分隔符字符串讀說線路。

實施例:

文件1包含:

green 
blue 
red 

文件2包含:

rain         
sun 

分隔符字符串= XX

輸出=

greenxxrain         
bluexxsun         
redxx 

我已經設法做到這一點,但想知道是否有其他人有任何替代品。這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int f1, f2; 
    FILE *file1, *file2; 

    file1 = fopen("textone", "r"); //open file1 for reading. 
    file2 = fopen("texttwo", "r"); //open file2 for reading. 

    //if there are two files ready, proceed. 
    if (file1 && file2){ 
     do{ 
      //read file1 until end of line or end of file is reached. 
      while ((f1 = getc(file1)) != '\n' && f1!= EOF ){ 
       //write character. 
       putchar(f1); 
      } 
      //print separator string. 
      printf("xx"); 
      //read file2 until end of line or end of file is reached. 
      while ((f2 = getc(file2)) != '\n' && f2!= EOF){ 
       //write character. 
       putchar(f2); 
      } 
      putchar('\n');  
     //do this until both files have reached their end. 
     }while(f1 != EOF || f2 != EOF); 
    } 
} 
+0

的精確副本:http://stackoverflow.com/questions/9555167/understanding-c-string-concatenation(爲此我創建了一個美麗的國家機器;-) – wildplasser 2012-03-08 00:44:58

+0

中查找['膏'](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/paste.html)命令。 – 2012-03-08 00:51:35

回答

1

您可能會感興趣fgets(3)有用。它可以用來一次讀取整行。也就是說,它也有缺點 - 例如,您需要知道線路將要運行多長時間,或者至少處理線路比緩衝區長的情況。你的實現對我來說似乎很好(除了你應該打電話fclose(3))。

+0

我想在主循環之後使用fclose()會是對的嗎? – user1255961 2012-03-08 01:08:39

+0

也文本文件可以是可變長度,我試圖使用fgets(),但想不到一種方式來合併行與分隔符 – user1255961 2012-03-08 01:10:02

+0

是的'fclose'問題,你不需要*需要*'fgets',你的實現是OK的。 – 2012-03-08 01:11:20

0

你可以寫一個簡單的功能,以避免在do { ... } while循環「大」的重複:

static void read_and_echo_line(FILE *fp) 
{ 
    int c; 
    while ((c = getc(fp)) != EOF && c != '\n') 
     putchar(c); 
} 


... 

    do 
    { 
     read_and_echo_line(file1); 
     printf("xx"); 
     read_and_echo_line(file2); 
     putchar('\n');  
    } while (!feof(file1) || !feof(file2)); 

在這種情況下,這是相當合理使用feof()如圖所示(儘管它不是一個函數大部分時間使用)。或者:

static int read_and_echo_line(FILE *fp) 
{ 
    int c; 
    while ((c = getc(fp)) != EOF && c != '\n') 
     putchar(c); 
    return(c); 
} 

... 

    do 
    { 
     f1 = read_and_echo_line(file1); 
     printf("xx"); 
     f2 = read_and_echo_line(file2); 
     putchar('\n');  
    } while (f1 != EOF || f2 != EOF); 
+0

非常感謝,非常感謝。 – user1255961 2012-03-08 01:07:16