linux文件系统编程 标准IO

fopen.c


#include



int main()
{
// FILE *fp = fopen("abc", "rb+");
FILE *fp = fopen("abc", "ab+");
if (fp == NULL)
{
perror ("fopen");
return -1;
}



printf ("打开文件成功\n");
    return 0;

}




fread.c

#include


#define SIZE 1024


int main()
{
// FILE *fp = fopen("abc", "rb+");
FILE *fp = fopen("BTree.c", "ab+");
if (fp == NULL)
{
perror ("fopen");
return -1;
}

char buf[SIZE] = {0};

// feof 判断是否读到文件结尾,如果读到文件结尾,它返回一个非0 的值
int ret;
while (ret = fread(buf, sizeof(char), SIZE-1, fp))
{
buf[ret*sizeof(char)] = '\0';
printf ("%s\n", buf);
}

if(ret == 0 && !feof(fp))
{
perror ("fread");
return -1;
}

printf ("文件读取结束\n");
    return 0;
}



fwrite.c

#include


#define SIZE 1024


int main()
{
// FILE *fp = fopen("abc", "rb+");
FILE *fp = fopen("1.ppt", "ab+");
if (fp == NULL)
{
perror ("fopen");
return -1;
}

FILE *fp1 = fopen("2.ppt", "ab+");
if (fp1 == NULL)
{
perror ("fopen");
return -1;
}

char buf[SIZE] = {0};

// feof 判断是否读到文件结尾,如果读到文件结尾,它返回一个非0 的值
int ret;
while (ret = fread(buf, sizeof(char), SIZE, fp))
{
fwrite(buf, sizeof(char), ret, fp1);
}

if(ret == 0 && !feof(fp))
{
perror ("fread");
return -1;
}

printf ("文件读取结束\n");

fclose(fp);
fclose(fp1);
    return 0;
}



fgetc.c

#include


#define SIZE 1024


int main()
{
// FILE *fp = fopen("abc", "rb+");
FILE *fp = fopen("1.ppt", "ab+");
if (fp == NULL)
{
perror ("fopen");
return -1;
}

FILE *fp1 = fopen("2.ppt", "ab+");
if (fp1 == NULL)
{
perror ("fopen");
return -1;
}

char buf[SIZE] = {0};

// feof 判断是否读到文件结尾,如果读到文件结尾,它返回一个非0 的值
int ret;
while (1)
{
int c = fgetc(fp);
if (c == EOF)
break;
fputc(c, fp1);
}

fclose(fp);
fclose(fp1);
    return 0;
}



数据读取.c

#include


#define SIZE 1024


typedef struct student
{
int  id;
char name[20];
}STU;




void write_data(STU *a)
{
FILE *fp = fopen("student", "ab+");
if (fp == NULL)
{
perror ("fopen");
return;
}


// 要写入个数
int len = sizeof(a)/sizeof(a[0]);
fwrite(&len, sizeof(int), 1, fp);
int i;
for (i = 0; i < len; i++)
{
// 写入数据长度
len = sizeof(a[i]);
fwrite(&len, sizeof(int), 1, fp);

// 写入数据
fwrite(&a[i], sizeof(STU), 1, fp);
}

fclose(fp);
}


void read_data()
{
FILE *fp = fopen("student", "ab+");
if (fp == NULL)
{
perror ("fopen");
return;
}


// 读记录的个数
int count;
fread (&count, sizeof(int), 1, fp);

printf ("记录个数是:%d\n", count);
int i;
STU tmp;
for (i = 0; i < count; i++)
{
int len;
fread (&len, sizeof(int), 1, fp);

// 读取数据
fread (&tmp, len, 1, fp);

printf ("id = %d, name = %s\n", tmp.id, tmp.name);
}

fclose(fp);
}


int main()
{


int i;
STU a[20];
for (i = 0; i < 20; i++)
{
a[i].id = i;
sprintf (a[i].name, "zhang%d", i);
}

// 写入数据
// write_data(a);

// 读数据
read_data();


    return 0;
}

你可能感兴趣的:(linux文件系统编程 标准IO)