2014-02-24 32 views
1

這個程序的目的是運行用戶指定的數據,所有的數據都格式化爲hw-data-3.txt,其中3可以從1到100不等。我需要遍歷指定的文件並加起來花費的總金額。每行最多有50個字符,包括\ n以及每個文件最多30行。我遇到了分段錯誤,我很確定這是一個指針問題,但我不確定它在哪裏。任何人都可以幫我找到它嗎?我的程序指針錯誤[C89]

#include <stdio.h> 
#include <stdlib.h> 
int main(int argc, char* argv[]) 
{ 
    char buff[255];int spent[30]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},i,z,intbuff[]={0,0,0,0}; 
    for(i=*argv[argc-2];i>=*argv[(argc-1)];i++) 
    { 
      sprintf(buff,"hw-data-%d.txt",i); 
      FILE *fp;fp=fopen(buff,"r"); /*Initializing and setting file pointer for unknown amount of files*/ 
      buff[0]='\0'; 
      while(!feof(fp)) /*while the end of file has not been reached for the stream continue doing these actions*/ 
      { 
       fgets(&buff[0],50,fp); /*captures 1 line at a time from stream then advances the streams position*/ 
       for(z=0;buff[z]!='\0';z++){ 
        if(buff[z]=='$') 
         break; /*breaks loop at position in line where $ occurs*/} 
       for (i=0;i<2;i++,z++){ 
        if (buff[z]=='0'||buff[z]=='1'||buff[z]=='2'||buff[z]=='3'||buff[z]=='4'||buff[z]=='5'||buff[z]=='6'||buff[z]=='7'||buff[z]=='8'||buff[z]=='9') 
         intbuff[i]=buff[z]; 
        else 
         break;}/* break statement is here to preserve number of integers after $, ie. $100 i=3 $33 i=2 $9 i=1 */ 
       for (;i>=0;--i) 
       { 
        intbuff[3]+=buff[i]; 
       }    
       for(i=0;i<30;i++) 
       {(spent[i]==0)?(spent[i]=intbuff[3]):(0);}/* If i in int array is 0 then replace 0 with the number captured.*/ 
      } 
      fclose(fp); 
    } 
    return(0); 
} 

回答

0

此行是問題:

for(i=*argv[argc-2];i>=*argv[(argc-1)];i++) 

argv[?]一個int。您必須使用strtol()系列函數之一將字符串轉換爲int。

你的代碼有許多其他的問題:

1)檢查用戶提供了足夠的參數(如你正在使用argv[])。

2)檢查返回值fopen()

3)while(!feof(fp))不可能是你想要的。 feof()告訴您是否讀過文件末尾。閱讀:Why is 「while (!feof (file))」 always wrong?

4)緩衝區intbuff[]只能保存四個整數,而您似乎存儲了與用戶自變量一樣多的整數。

0

while (!feof(fp))是一個不好的做法。
你假設fgets()成功。

嘗試這樣:

while (fgets(&buff[0],50,fp) != NULL) 

此行並沒有太大的意義之一:

for(i=*argv[argc-2];i>=*argv[(argc-1)];i++) 

我會嘗試有些設置你這樣的代碼:

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

#define LINE_LENGTH 50 
#define MAX_LINES 30 

int main (int argc, char *argv []) 
{ 
    int i ; 

    char buffer [LINE_LENGTH] = {0} ; 

    // Assuming argv[0] is the program name. 
    for (i = 1; i < argc; ++i) { 
     FILE *fp ; 
     fp = fopen (argv [i], "r") ; 

     if (fp == NULL) { 
      // Handle error... 
     } 

     while (fgets (buffer, LINE_LENGTH, fp) != NULL) { 
      // ... 
     } 
    } 

    return 0 ; 
}; 
0

argv[argc-2]是一個c-string(char *類型)。解除引用後,您將獲得第一個字符。然後,您將ASCII值轉換爲一個int值 - 不會給出該char的實際值(更不用說該參數的整個數值) - 而是使用參數atoi來獲得實數整數。