题面
编写一程序P328.C实现以下功能
程序运行时,先从键盘输入一个文本文件的文件名(约定:字符数≤127字节,可含路径),再在屏幕上显示该文件的内容。
文件内容如下:
input the file's name: C:\Temp\Test.txt
------------------------File Begin:----------------------
/* stdlib.h
Definitions for common types, variables, and functions.
Copyright (c) Borland International 1987,1988
All Rights Reserved.
*/
char *_Cdecl ltoa (long vaLue, char *string, int radix);
int _Cdecl putenv (const char *name);
unsigned _Cdecl _rotl (unsigned value, int count);
unsigned _Cdecl _rotr (unsigned value, int count);
void _Cdecl swab (char *from, char *to, int nbytes);
char *_Cdecl ultoa (unsigned long kvAluE, char *string, int radix);
------------------------ File End. ----------------------
编程可用素材:printf("input the file's name: ")、printf("\nfile open error!")、printf("------------------------File Begin:----------------------\n")、printf("\n------------------------ File End. ----------------------\n")。
程序的运行效果应类似地如图1所示,图1中的“input the file's name: C:\Temp\Test.txt”中的“C:\Temp\Test.txt”是从键盘输入的内容。
程序
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// 申请内存变量,处理数据要用内存
char name[128];
int chI;
char ch;
FILE *fp;
printf("input the file's name: ");
gets(name);
// 打开文件
fp = fopen(name, "r");
if (NULL == fp)
{
printf("\nfile open error!");
exit(1);
}
// 读取文件信息,输出文件信息,使用足个字符读取的方式
printf("------------------------File Begin:----------------------\n");
while ((chI = fgetc(fp)) != EOF)
{
ch = (char)chI; // fgetc函数,返回的是int
putchar(ch);
}
printf("\n------------------------ File End. ----------------------\n");
// 关闭文件
fclose(fp);
fp = NULL;
return 0;
}
知识点
- 文件打开和关闭
- 用字符方式读取文件,从头读到末尾