2014-02-24 30 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来获得实数整数。