用C语言写一个程序,功能是从result1.txt文档中读取一个整数,一个字符,一个实数,并输出到屏幕上
时间: 2023-05-16 21:05:51 浏览: 76
以下是用C语言编写的程序,可以实现从result1.txt文档中读取一个整数、一个字符和一个实数,并将它们输出到屏幕上:
```c
#include <stdio.h>
int main() {
int num;
char ch;
float fnum;
FILE *fp = fopen("result1.txt", "r");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
fscanf(fp, "%d %c %f", &num, &ch, &fnum);
printf("%d %c %f\n", num, ch, fnum);
fclose(fp);
return 0;
}
```
这个程序首先打开名为result1.txt的文件,然后使用fscanf函数从文件中读取一个整数、一个字符和一个实数,并将它们存储在num、ch和fnum变量中。最后,使用printf函数将这些变量的值输出到屏幕上。
相关问题
用C语言写一个程序,功能是从键盘上依次输入一个整数1234、一个字符a、一个实数5.6,用fprintf函数写入文件result.txt中。
以下是用C语言编写的程序,可以实现从键盘上依次输入一个整数1234、一个字符a、一个实数5.6,并将它们写入文件result.txt中:
```c
#include <stdio.h>
int main() {
int num = 1234;
char ch = 'a';
float fnum = 5.6;
FILE *fp = fopen("result.txt", "w");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
fprintf(fp, "%d %c %.1f", num, ch, fnum);
fclose(fp);
return 0;
}
```
这个程序中,我们首先定义了一个整数、一个字符和一个实数,并将它们赋值为1234、'a'和5.6。然后,我们使用fopen函数打开文件result.txt,并将文件指针保存在变量fp中。如果打开文件失败,我们会输出一条错误信息并返回1。接着,我们使用fprintf函数将整数、字符和实数写入文件result.txt中。最后,我们使用fclose函数关闭文件。
请用C语言写一个将数据从txt文件中读取并存入链表的函数
好的,以下是一个简单的C语言函数,可以将数据从txt文件中读取并存入链表中:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *readFile(char *filename) {
FILE *fp;
Node *head = NULL, *tail = NULL;
int num;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return NULL;
}
while (fscanf(fp, "%d", &num) == 1) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
fclose(fp);
return head;
}
```
这个函数接受一个文件名作为参数,打开文件并读取其中的整数数据,然后将这些数据存入一个链表中,并返回链表的头指针。如果文件无法打开,则函数返回NULL。