c语言 指针存入文件
时间: 2023-12-08 09:32:05 浏览: 80
C语言中可以使用文件指针将指针存入文件中。首先,需要使用`fopen()`函数打开一个文件,并将文件指针赋值给一个指针变量。接下来,可以使用`fprintf()`函数将指针的值写入文件。最后,使用`fclose()`函数关闭文件。
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp; // 文件指针
int *ptr; // 指针变量
int value = 10;
// 打开文件
fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("File cannot open! ");
exit(0);
}
// 将指针的值写入文件
ptr = &value;
fprintf(fp, "%p", (void*)ptr);
// 关闭文件
fclose(fp);
return 0;
}
```
相关问题
c语言实现读取文件存入链表
在 C 语言中,可以使用 `fopen` 函数打开文件,然后使用 `fscanf` 函数读取文件中的数据。我们可以在读取数据的同时,动态创建链表节点,并将读取到的数据存储在节点中。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
} Node;
int main() {
char filename[100]; // 文件名
scanf("%s", filename);
FILE* fp = fopen(filename, "r"); // 打开文件
if (fp == NULL) { // 文件打开失败
printf("Failed to open file.\n");
return 1;
}
Node* head = NULL; // 头指针初始为空
// 读取文件并创建链表
int data;
while (fscanf(fp, "%d", &data) != EOF) {
Node* node = (Node*)malloc(sizeof(Node)); // 创建新节点
node->data = data; // 存储数据
if (head == NULL) { // 如果链表为空,将头指针指向新节点
head = node;
} else { // 如果链表不为空,将新节点插入到链表尾部
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
}
// 打印链表
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
// 释放链表内存
p = head;
while (p != NULL) {
Node* q = p;
p = p->next;
free(q);
}
fclose(fp); // 关闭文件
return 0;
}
```
在这个示例代码中,我们首先读入文件名,然后使用 `fopen` 函数打开文件。如果文件打开失败,我们将输出一条错误消息并退出程序。
接着,我们循环使用 `fscanf` 函数读取文件中的数据。在读取到数据时,我们首先使用 `malloc` 函数动态分配内存创建新节点,并将读取到的数据存储在节点中。如果链表为空,我们将头指针指向新节点;否则,我们将新节点插入到链表尾部。
创建链表后,我们循环遍历链表并打印每个节点存储的数据,然后释放链表内存。最后,我们使用 `fclose` 函数关闭文件。
c语言如何向文件中存入内容
在C语言中,向文件中存入内容需要使用文件操作函数,主要包括打开文件、写入文件和关闭文件三个步骤。具体实现方法如下:
1. 打开文件
使用fopen函数打开文件,该函数的原型如下:
```
FILE *fopen(const char *filename, const char *mode);
```
其中,filename为要打开的文件名,mode为打开文件的模式,常用的模式有:
- "r":只读打开,文件必须存在
- "w":写打开,如果文件存在则清空,如果文件不存在则创建
- "a":追加打开,如果文件存在则在文件末尾追加,如果文件不存在则创建
示例代码:
```c
FILE *fp;
fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("打开文件失败\n");
exit(1);
}
```
2. 写入文件
使用fwrite函数向文件写入内容,该函数的原型如下:
```
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
```
其中,ptr为要写入文件的数据的指针,size为每个数据块的大小,count为数据块的数量,stream为文件指针。
示例代码:
```c
char str[] = "hello world";
fwrite(str, sizeof(char), strlen(str), fp);
```
3. 关闭文件
使用fclose函数关闭文件,该函数的原型如下:
```
int fclose(FILE *stream);
```
其中,stream为文件指针。
示例代码:
```c
fclose(fp);
```
完整示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp;
char str[] = "hello world";
fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("打开文件失败\n");
exit(1);
}
fwrite(str, sizeof(char), strlen(str), fp);
fclose(fp);
return 0;
}
```