B
Barry Schwarz
"Frank" <[email protected]> ha scritto nel messaggio
i rewrote the last code in your post with some comment
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int exptab(int n, const char *path)
{FILE *fin, *fout;
char *path_exp,
*exp_suffix = ".exp";
int c, nc;
// why not to do some test for input?
if(n<0||n>999||path==0||*path==0) return EXIT_FAILURE;
nc=strlen(path); if(nc<0||nc>999) return EXIT_FAILURE;
strlen returns a size_t which is guaranteed to be unsigned. What are
the odds it can ever be less than 0? On the other hand, you don't
consider nc equal to 0 to be a problem but I don't know of any system
which supports zero-length path names.
c =strlen(exp_suffix); if(c <0||c >999) return EXIT_FAILURE;
nc+=c;
path_exp = malloc(nc + 1);
if(!path_exp)
{fprintf(stderr, "%s: %s\n", "exptab", "malloc error");
Why bother with formats for hard coded strings?
return EXIT_FAILURE;
}
strcat(strcpy(path_exp, path), exp_suffix);
fout = fopen(path_exp, "w");
free(path_exp);
if(!fout){fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, "fopen");
return EXIT_FAILURE;
}
Your coding style makes finding the corresponding { a pain.
fin = fopen(path, "r");
if(!fin){fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, "fopen");
fclose(fout);
return EXIT_FAILURE;
}
while( (c=fgetc(fin)) != EOF )
{if(c == '\t')
{nc=n;
while(nc--)
fputc(' ', fout);
}
else fputc(c, fout);
}
c=0;
// why not see it there are problem in the files?
if( fclose(fin) ==EOF ) c=1;
if( fclose(fout)==EOF ) c=1;
return c==1?
(fprintf(stderr, "%s(%d): %s\n",
__FILE__, __LINE__,"other"),EXIT_FAILURE):
0;
}
/*test*/
#include <errno.h>
int main(int argc, char *argv[])
{long n;
char *endp;
int errnoStrtol;
if(argc != 3){fprintf(stderr, "%s: <num> <filename>\n", argv[0]);
return EXIT_FAILURE;
}
errno=0;
n=strtol(argv[1], &endp, 10);
errnoStrtol=errno;
// print some values
printf("argv1 is %ld\n" , n);
fprintf(stderr, "stderr has the following error %d\n ", errno);
printf(" errno is %d\n" , errnoStrtol);
printf(" endp is %p\n" , endp);
// printf(" endp points to %p\n" , (void*)*endp);
// have not mening: in strtol what is changed is the endp
// value, for this there is **endp, in the definition of
// strtol because for change char* endp; i have to
// pass to the function char** and so &endp
if(endp!=0)
printf(" the pointer to endp points to [%c]:[%d]\n" ,
endp[0], (int)endp[0]);
if ( // *endp!=0 || in general should be meanigless
errnoStrtol)
{perror("main"); return EXIT_FAILURE;}
return exptab( atoi(argv[1]), argv[2]);
Why convert argv again? The value is already in n.