编程题
1、读文件file1.txt的内容(例如):
123456
输出到file2.txt:
563412
#include <stdio.h> #include <stdlib.h> int main(void) { int MAX = 10; int *a = (int *)malloc(MAX * sizeof(int)); int *b; FILE *fp1; FILE *fp2; fp1 = fopen("a.txt","r"); if(fp1 == NULL) { printf("error1"); exit(-1); } fp2 = fopen("b.txt","w"); if(fp2 == NULL) { printf("error2"); exit(-1); } int i = 0; int j = 0; while(fscanf(fp1,"%d",&a[i]) != EOF) { i++;j++; if(i >= MAX) { MAX = 2 * MAX; b = (int*)realloc(a,MAX * sizeof(int)); if(b == NULL) { printf("error3"); exit(-1); } a = b; } } for(;--j >= 0;) fprintf(fp2,"%d ",a[j]); fclose(fp1); fclose(fp2); return 0; }
对1的另一种做法:
1 #include <stdio.h> 2 void test(FILE *fread, FILE *fwrite) 3 { 4 char buf[1024] = {0}; 5 if (!fgets(buf, sizeof(buf), fread)) 6 return; 7 test( fread, fwrite ); 8 fputs(buf, fwrite); 9 } 10 int main(int argc, char *argv[]) 11 { 12 FILE *fr = NULL; 13 FILE *fw = NULL; 14 fr = fopen("data", "rb"); 15 fw = fopen("dataout", "wb"); 16 test(fr, fw); 17 fclose(fr); 18 fclose(fw); 19 return 0; 20 }
2、输出和为一个给定整数的所有组合
例如n=5
5=1+4;5=2+3(相加的数不能重复)
则输出
1,4;2,3。
1 #include <stdio.h> 2 int main(void) 3 { 4 unsigned long int i,j,k; 5 printf("please input the number "); 6 scanf("%d",&i); 7 if( i % 2 == 0) 8 j = i / 2; 9 else 10 j = i / 2 + 1; 11 printf("The result is "); 12 for(k = 0; k < j; k++) 13 printf("%d = %d + %d ",i,k,i - k); 14 15 return 0; 16 }
或
1 #include <stdio.h> 2 void main() 3 { 4 unsigned long int a,i=1; 5 scanf("%d",&a); 6 if(a%2==0) 7 { 8 for(i=1;i<a/2;i++) 9 printf("%d",a,a-i); 10 } 11 else 12 for(i=1;i<=a/2;i++) 13 printf(" %d, %d",i,a-i); 14 }
3、递规反向输出字符串的例子,可谓是反序的经典例程.
void inverse(char *p) { if( *p = = '