2014-03-29 24 views
0

所以我目前正在爲我的代碼收到一個分段錯誤,並試圖縮小它的可能範圍。我不確定fgetc函數的起點是否與fprintfscanf的位置相同。fgetc c的起點

即即使我在文件上使用了scanf,然後使用fgetc它會從一開始就開始還是繼續scanf的停止位置?如果是前者,我將如何去操縱起點?

//reads the second line of the input file in order to grab the ten numbers in the line 
int numRead = fscanf(Data, "\n %d %d %d %d %d %d %d %d %d %d", &zero, &one, 
     &two, &three, &four, &five, &six, &seven, &eight, &nine); 

while(EOF != (c = fgetc(Data))) 
{ 
    message[i] = c; 
    i++; 
} 

輸入文件:

0 1 2 3 4 5 6 7 8 9 
6 7 8 0 1 9 5 2 3 4 
If I were reincarnated, I'd want to come back a 
buzzard. Nothing hates him or envies him or wants 
him or needs him. He is never bothered or in 
danger, and he can eat anything. 
-- Mark Twain 
+3

它將繼續在那裏scanf停止。但是:有時scanf在與fgetc,fgets等混合時非常討厭。反正,顯示你的代碼,沒有我們找不到任何段錯誤。 – deviantfan

+1

使用valgrind,它可能會查明你的問題。 –

+1

另外,使用編譯器可以提供的所有警告進行編譯。瞭解它爲什麼會發出警告並解決問題。 – Deduplicator

回答

0

在循環裏fgetc通話將十分開始,其中fscanf完成,但你應該知道這一點,將會是下一個字符的最後一個項目之後掃描。假設它工作正常,那將是第二行結尾處的\n字符(假設你在該行的開頭,這似乎是你的代碼註釋的情況)。

因此,第一個fgetc會給你上述的\n,下一個會在第三行開始時給你'I',依此類推。

如果發生崩潰,我會馬上檢查幾件事情。

第一個是cint類型而不是char。這是需要的,以便您可以從它接收任何有效的char類型EOF指示器。

第二個是message足夠大以容納數據。

第三個是i初始化爲零。

您應該也許應該檢查您的掃描是否工作以讀取十個數字,以確保安全。

查看下面的完整程序,瞭解如何做到這一點。你會注意到我還檢查以確保緩衝區不會溢出由於過於文件中的數據是:

#include<stdio.h> 

int main(void) 
{ 
    // Open file for reading. 

    FILE *Data = fopen ("qq.in", "r"); 
    if (Data == NULL) { 
     puts ("Cannot open qq.in"); 
     return 1; 
    } 

    // Skip first and second line (twenty numbers). 

    int zero, one, two, three, four, five, six, seven, eight, nine; 

    int numRead = fscanf(Data, "%d %d %d %d %d %d %d %d %d %d", &zero, &one, 
     &two, &three, &four, &five, &six, &seven, &eight, &nine); 
    if (numRead != 10) { 
     puts ("Could not read first ten integers"); 
     fclose (Data); 
     return 1; 
    } 

    numRead = fscanf(Data, "%d %d %d %d %d %d %d %d %d %d", &zero, &one, 
     &two, &three, &four, &five, &six, &seven, &eight, &nine); 
    if (numRead != 10) { 
     puts ("Could not read second ten integers"); 
     fclose (Data); 
     return 1; 
    } 

    // Loop for reading rest of text (note initial newline here). 

    int c, i = 0; 
    char message[1000]; 

    while(EOF != (c = fgetc(Data))) { 
     if (i >= sizeof(message)) { 
      puts ("Too much data"); 
      fclose (Data); 
      return 1; 
     } 
     message[i++] = c; 
    } 

    fclose (Data); 

    printf ("[%*.*s]\n", i, i, message); 

    return 0; 
} 

運行時,這將產生:

[ 
If I were reincarnated, I'd want to come back a 
buzzard. Nothing hates him or envies him or wants 
him or needs him. He is never bothered or in 
danger, and he can eat anything. 
-- Mark Twain 
]