2013-04-18 39 views
0

我真的很新的C,很抱歉,如果這是一個愚蠢的問題,但讓我們說我有一個包含文件如下:(?或字符)如何從文件中提取一行的一部分?

1 abc 
2 def 
3 ghi 

如果我在整數關口像3函數將返回一串「ghi」。我不知道如何做到這一點。

void testFunc(int num) 
{ 
     FILE *fp; 
     fp = fopen("testfile.txt", "r"); 

     if(strstr?????? 
} 

是的..我不知道我在做什麼。任何人都可以提供任何指導嗎?

+1

所有的信息:「我不知道」是不好的。肯定有**的東西,你可以拿出來。甚至不需要知道C.只需考慮算法。這是微不足道的。 – 2013-04-18 04:35:49

+0

在www上搜索fopen的例子 – 2013-04-18 04:37:10

+0

首先寫一個條件來檢查字符'3'....當這個字符發現後你可以提取字符串.. like'while(ch = fgetc(fp)!= EOF) if(ch =='3') { //提取STRING直到出現新行。 } }' – umang2203 2013-04-18 04:37:40

回答

0

試試這個代碼

void testFunc(int num) 
{ 
    FILE *file = fopen ("testfile.txt", "r"); 
    char line [ 128 ]; /* or other suitable maximum line size */ 
    if (file != NULL) 
    { 
      while (fgets (line, sizeof(line), file) != NULL) /* read a line */ 
      { 
       fputs (line, stdout); /* write the line */ 
      } 
    fclose (file); 
    } 
} 
0
//input:num, output:string, string is call side cstring area. 
void testFunc(int num, char *string){ 
    FILE *fp; 
    int n; 

    fp = fopen("data.txt", "r"); 
    while(2==fscanf(fp, "%d %s ", &n, string)){ 
     if(num == n){ 
      printf("%s\n",string); 
      break; 
     } 
    } 
    fclose(fp); 
    return; 
} 
1

使用與fgets讀取每個行 使用的sscanf到每一行的第一和第二元件保存到變量 測試是否數量= 3,並且如果是這樣印字。

的手冊頁應該給你你需要使用與fgetssscanf的