267、文件中写入了什么,屏幕上显示了什么?以下是代码:#include int main(void) { FILE *fp[2]; if((fp[0] = fp[1] = fopen(“test.txt”, “w”)) != NULL) { fputs(“One”, fp[0]); fclose(fp[0]); printf(“%d
”, fputs(“Two”, fp[1])); fclose(fp[1]); } return 0; }
文件中写入了One,屏幕上显示了EOF(文件结束符)的值。
268、编写一个程序,用于将一些数据写入文件。该程序应读取一个文件名,如果文件不存在,程序应创建该文件并将字符串“One”写入其中。如果文件已存在,程序应询问用户是否覆盖它。如果用户回答是肯定的,程序应将字符串“One”写入其中;否则,程序应提示用户输入另一个文件名,以重复相同的过程。
#include <stdio.h>
#include <stdlib.h>
FILE *open_file(char name[], int *f);
int main(void) {
FILE *fp;
char name[100];
int flag, sel;
flag = 0;
do {
printf("Enter file name: ");
scanf("%s", name);
fp = fopen(name, "r");
/* Check whether the file exists or not. If not, we open it for writing. Otherwise, we close the file and ask the user. */
if (fp == NULL)
fp = open_file(name, &flag);
else {
fclose(fp);
printf("Would you like to overwrite existing file (Yes:1 - No:0)? ");
scanf("%d", &sel);
if (sel == 1)
/* Overwrite the file. */
fp = open_file(name, &flag);
}
} while (flag == 0);
fputs("One", fp);
fclose(fp);
return 0;
}
FILE *open_file(char name[], int *f) {
FILE *fp;
fp = fopen(name, "w");
if (fp == NULL) {
printf("Error: fopen() failed\n");
exit(EXIT_FAILURE);
}
*f = 1;
return fp;
}
269、编写一个程序,读取产品代码(每个代码少于20个字符)及其价格,并将它们存储在一个文本文件中,格式如下:C101 17.5 C102 32.8 … 如果用户输入价格为 -1,则产品录入应终止。然后,程序应读取一个产品代码,并在文件中搜索该代码,找到并显示其价格。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_text(char str[], int size, int flag);
int main(void) {
FILE *fp;
char flag, str[20], prod[20];
double prc;
fp = fopen("test.txt", "w+"); /* 打开文件进行读写操作 */
if (fp == NULL) {
printf("Error: fopen() failed\n");
exit(EXIT_FAILURE);
}
while (1) {
printf("Enter price: ");
scanf("%lf", &prc);
if (prc == -1)
break;
getchar();
printf("Enter product code: ");
read_text(str, sizeof(str), 1);
fprintf(fp, "%s %f\n", str, prc);
}
getchar();
printf("Enter product code to search for: "

最低0.47元/天 解锁文章
767

被折叠的 条评论
为什么被折叠?



