c语言文件的读取和写入
时间: 2024-05-29 20:08:54 浏览: 17
好的,关于c语言文件的读取和写入,我可以给您一些基本的介绍。
首先,在c语言中,可以使用标准库函数来操作文件。比如,可以使用fopen函数打开一个文件,使用fprintf函数向文件中写入数据,使用fscanf函数从文件中读取数据,使用fclose函数关闭文件。
具体使用方法可以参考c语言的相关文档或者教程,另外也可以在网上查找一些代码示例来学习。
希望这个回答能够帮助到您,如果有其他问题可以继续问我哦。而现在,您可以问我您接下来想问的问题。
相关问题
c语言文件读取并写入链表
以下是一个示例的C语言代码,用于读取文件并将数据存储到链表中:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
char name[50];
char adr[50];
int tel;
struct student* next;
} Student;
Student* createNode() {
Student* newNode = (Student*)malloc(sizeof(Student));
newNode->next = NULL;
return newNode;
}
void insertNode(Student** head, Student* newNode) {
if (*head == NULL) {
*head = newNode;
} else {
Student* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void readFile(char* filename, Student** head) {
FILE* fp;
if ((fp = fopen(filename, "r")) == NULL) {
printf("Cannot open file\n");
exit(1);
}
int n;
printf("How many students? ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
Student* newNode = createNode(); fscanf(fp, "%s", newNode->name);
fscanf(fp, "%s", newNode->adr);
fscanf(fp, "%d", &(newNode->tel));
insertNode(head, newNode);
}
fclose(fp);
}
void displayList(Student* head) {
Student* temp = head;
while (temp != NULL) {
printf("%10s%15s%15d\n", temp->name, temp->adr, temp->tel);
temp = temp->next;
}
}
void freeList(Student* head) {
Student* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main(void) {
char filename[50];
printf("Please input filename: ");
scanf("%s", filename);
Student* head = NULL;
readFile(filename, &head);
displayList(head);
freeList(head);
system("pause");
return 0;
}
```
用C语言完成文件读取和写入
好的,下面是用C语言完成文件读取和写入的示例代码:
文件读取:
```
#include <stdio.h>
int main() {
FILE *fp;
char buffer[100];
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("无法打开文件!\n");
return 1;
}
while (fgets(buffer, 100, fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}
```
文件写入:
```
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("无法打开文件!\n");
return 1;
}
fprintf(fp, "Hello, world!");
fclose(fp);
return 0;
}
```
以上代码中,`example.txt` 是待读取或写入的文件名,`r` 和 `w` 分别表示读取和写入。在读取文件时,我们使用 `fgets` 函数逐行读取文件内容,并输出到控制台;在写入文件时,我们使用 `fprintf` 函数将字符串写入文件中。最后,别忘了关闭文件,以释放资源。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)