C程序设计 (第四版) 谭浩强 例10.1 例10.1 从键盘输入一些字符,逐个把它们送到磁盘上去,直到用户输入一个“#”为止。 IDE工具:VS2010 Note: 使用不同的IDE工具可能有部分差异。 代码块 方法:使用指针,函数的模块化设计,动态分配内存 说明:这里要写入的文件名称为Test.txt,已经存在于该项目目录下。 #include <stdio.h> #include <stdlib.h> void initialFile(FILE **file, char **word){ *file = (FILE*)malloc(sizeof(FILE)); *word = (char*)malloc(sizeof(char)); } void inputFileName(FILE **file){ char name[80]; printf("Enter File Name: "); scanf("%s", name); *file = fopen(name, "r"); if(*file == NULL){ perror("Cannot open this file"); system("pause"); exit(0); } *file = fopen(name, "w+"); } void fileInput(char *word, FILE **file){ printf("Enter String: "); while((*word = getchar()) != '#'){ fputc(*word, *file); } } int main(){ FILE *file = NULL; char *word = NULL; initialFile(&file, &word); inputFileName(&file); fileInput(word, &file); fclose(file); putchar(10); system("pause"); return 0; } 运行结果如下: