`
一、lseek
1.lseek用法介绍
lseek:用来调整光标的位置
lseek(文件描述符,光标移动的位置数,光标移动的形式)
SEEK_SET:将光标移动到文件开头再增加相应的offset位置
SEEK_CUR:将光标移动到文件的当前位置再往后加offset的位置
SEEK_END:将光标移动到文件的末尾再增加offset的位置
lseek函数返回值:返回值是从文件开头到光标位置有多少个字符
上次笔记有完整代码
2.ftruncate的作用
ftruncate:将指定的文件大小修改成length指定的大小(用来给文件扩容,如果指定的大小小于当前文件,接删除后面的程序)
ftruncate:(int fd, length)(计算长度)
ftruncate(fd ,0)(清楚数据)
stdio.h:C的标准输入输出库:I/O(input output)
file*
1、stdout:输出流
行缓冲:stdout在终端上进行输出的时候,输出的规则为每当出现换行符的时候进行一次刷新缓存,然后再进行操作(printf输出的时候,是看换行符才进行输出)
代码
#include<stdio.h>
#include<unistd.h>
int main() {
int a;
printf("111111111!\n");
scanf("%d" ,&a);
sleep (3);
printf("22222222222");
sleep (3);
printf("3333333333!\n");
return 0;
}
二、fopen
1.C语言中fopen的使用及参数含义
fopen():r:只读
w:只写 如果文件不存在,创建一个新的,如果文件存在,清空原先文件的文件内容
a:追加:不存在,创建一个新的,如果存在在文件末尾进行追加
r+:可读可写,文件不存在,打开失败
w+:w + r+
a+:a + r+
fclose(fp)
代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
fp=fopen("text.txt", "w+");
if(NULL == fp)
{
perror("fopen!");
exit(1);
}
fclose(fp);
return 0;
}
2.fread的使用
fread
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
prt:字符串指针
size:读取每个字符的大小
nmemb:读取多少个
stream:文件描述符指针
代码
#include<string.h>
int main()
{
FILE *fp;
fp = fopen("./text.txt", "w+");
if(NULL == fp)
{
perror("open!");
exit(1);
}
char *str = "hello world!";
fwrite(str, sizeof(char), strlen(str),fp);
fclose(fp);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp;
fp = fopen("./text.txt", "w+");
if(NULL == fp)
{
perror("open!");
exit(1);
}
char *str = "hello world!";
int number = fwrite(str, sizeof(char), strlen(str),fp);
if(0 == number)
{
perror("fwrite:");
fclose(fp);
exit(1);
}
fclose(fp);
return 0;
}
3.fseek的使用
fseek
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp;
fp = fopen("./text.txt", "w+");
if(NULL == fp)
{
perror("open!");
exit(1);
}
char *str = "hello world!";
int number = fwrite(str, sizeof(char), strlen(str),fp);
if(0 == number)
{
perror("fwrite:");
fclose(fp);
exit(1);
}
fseek(fp, 0, SEEK_SET);
char buffer[1024] = {0};
int number2 = fread(buffer, sizeof(char), 1024, fp);
if(0 == number2)
{
perror("fread");
fclose(fp);
exit(1);
}
printf("read:%s\n",buffer);
fclose(fp);
return 0;
}
3.读字符家族
读字符家族:
getc:从文件里读取一个字符getc(fp)返回值:
当读到文件末尾五字符时,返回EOF(NULL)
fgetc:函数调用
getchar():
将字符从unsigned char 转换成int进行返回
带走缓冲区里多余的换行符
代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int c;
int i = 0;
for(i=0; i<5; i++)
{
c = getchar;
printf("%c",c);
}
printf("\n");
return 0;
}