先看一个程序段:
//文件名字为test.c #include #include #include int main(int argc, char *argv[]) { char ch2; FILE *fp; int i; fp = fopen(argv[1], "rt"); if(fp == NULL) { perror("fopen:"); } while((ch2 = fgetc(fp)) != EOF) { printf("%c", ch2); } fclose(fp); return 0; } |
在命令行中进行如下命令:
gcc test.c
./a.out sun.txt
注:假如在同目录下有一个文件sun.txt,里面内容为:
天亮了
上面的执行结果将为:
天亮了
如果将上面的程序改为如下:
//文件名字为test.c #include #include #include int main(int argc, char *argv[]) { char ch1[20] = {0}, ch2; FILE *fp; int i = 0, j; fp = fopen(argv[1], "rt"); if(fp == NULL) { perror("fopen:"); } while((ch2 = fgetc(fp)) != EOF) { printf("%c", ch2); ch1[i++] = ch2; } i = strlen(ch1); for(j = 0; j < i - 1; j++) { printf("ch1[%d]=%c\n", j, ch1[j]); } printf("%c%c%c\n", ch1[0], ch1[1], ch1[2]); printf("%c%c\n", ch1[0], ch1[1]); printf("%c%c\n", ch1[1], ch1[2]); fclose(fp); return 0; } |
在命令行中进行如下命令:
gcc test.c
./a.out sun.txt
注:假如在同目录下有一个文件sun.txt,里面内容为:
天亮了
上面的执行结果将为:
天亮了
ch1[0]=
ch1[1]=