[讨论]c语言提高练习题⒈
设d盘根目录下有一个名为“aaaa.dat”的二进制文件,其中连续存放了100个整数。编成实现下面要求:(1)读取其中的奇数编号(从0开始编号)的整数并输出;(2)读取并输出第99个整数和第100个整数。
程序代码:
#include <stdio.h>
#include <stdlib.h>
/* create the data file */
void createFile(void);
/* our function to read the odd's data */
void readOdd(void);
/* read the last too data */
void readLast(void);
int main(void)
{
createFile();
printf("The odd's numbers:\n");
readOdd();
printf("\nThe last two numbers:\n");
readLast();
return 0;
}
void createFile(void)
{
FILE *fp;
int i;
fp = fopen("aaa.dat", "wb");
if(fp == NULL) {
printf("Can not open file!\n");
exit(1);
}
/* write 100 integers into the file */
for(i = 0; i < 100; i++)
putw(i, fp);
fclose(fp);
}
void readOdd(void)
{
FILE *fp;
int i;
int data;
fp = fopen("aaa.dat", "rb");
if(fp == NULL) {
printf("Can not open file!\n");
exit(1);
}
for(i = 0; i < 100; i++) {
data = getw(fp);
if(i%2 != 0)
printf("%d\t", data);
}
fclose(fp);
}
void readLast(void)
{
FILE *fp;
int i99, i100;
fp = fopen("aaa.dat", "rb");
if(fp == NULL) {
printf("Can not open file!\n");
exit(1);
}
fseek(fp, -(long)2*sizeof(int), SEEK_END); /* find the right place */
i99 = getw(fp);
i100 = getw(fp);
printf("%d, %d\n", i99, i100);
fclose(fp);
}
