1.使用fread去实现fgetc函数
#include "/home/ubuntu/IO/myinc.h"
int my_fgetc(FILE *steam)
{
char ch;
if(NULL == steam)
{
perror("EOF:");
return -1;
}
size_t num;
num = fread(&ch,1,1,steam);
if(0 == num)
{
return -1;
}
return (int)ch;
}
int main(int argc, const char *argv[])
{
FILE* fp=fopen("1.txt","r");
if(NULL == fp)
{
perror("文件读取失败");
return -1;
}
int ch;
while((ch=my_fgetc(fp)) != -1 )
{
putchar(ch);
}
return 0;
}
2.使用fwrite去实现fputc函数
#include "/home/ubuntu/IO/myinc.h"
int my_fputc(char buf,FILE *steam)
{
char ch=buf;
size_t num;
if(steam == NULL )
{
perror("输入文件失败");
return -1;
}
num=fwrite(&ch,1,1,steam);
if(num==0)
{
printf("写入失败\n");
return -1;
}
}
int main(int argc, const char *argv[])
{
char buf='a';
FILE *fp=fopen("1.txt","a");
if(NULL == fp)
{
printf("打开文件1.txt失败\n");
return -1;
}
int a;
a=my_fputc(buf,fp);
return 0;
}
3.realloc()的使用方法
realloc 函数用于调整之前由 malloc、calloc 或 realloc 本身分配的内存块的大小。如果调整后的内存块变大,realloc 可能会将内存块移动到新的地址。如果内存块变小,它将保持在相同的地址。
函数原型:
void *realloc(void *ptr, size_t new_size);
ptr:指向之前分配的内存块的指针。如果 ptr 为 NULL,则 realloc 表现得像 malloc,尝试分配一个新的内存块。
new_size:新的内存块大小,以字节为单位。
返回值:
- 成功时,返回指向重新分配的内存块的指针。
- 失败时(如内存不足),返回
NULL
。
使用方法:
1.扩大内存块:如果需要更多的内存空间,可以调用 realloc 来扩大内存块,并更新指针。
2.缩小内存块:如果不再需要那么多内存,可以调用 realloc 来缩小内存块。
3.内存块移动:如果内存块被扩大,它可能会被移动到新的内存地址。因此,在使用返回的指针之前,应该更新所有指向原始内存块的指针。
示例代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)malloc(4 * sizeof(int)); // 分配内存以存储4个整数
if (array == NULL) {
perror("Memory allocation failed");
return 1;
}
// 初始内存块使用
for (int i = 0; i < 4; i++) {
array[i] = i * i;
}
// 需要更多的空间
array = (int *)realloc(array, 6 * sizeof(int)); // 尝试扩大内存块
if (array == NULL) {
perror("Memory reallocation failed");
return 1;
}
// 现在可以安全地使用array存储6个整数
for (int i = 4; i < 6; i++) {
array[i] = i * i;
}
// 打印数组内容
for (int i = 0; i < 6; i++) {
printf("%d ", array[i]);
}
printf("\n");
free(array); // 释放内存
return 0;
}
注意事项:
- 使用
realloc
时,应该总是检查返回值以确保内存重新分配成功。 - 如果
realloc
失败,原始的内存块不会被释放或移动,因此原始指针仍然有效。 - 如果
realloc
成功并且内存块被移动,原始指针将不再有效,必须使用返回的新指针。 - 永远不要假设
realloc
会返回原始指针。