用fgetc方法
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
int num=0;
fp=fopen("zi.tex","r");
while ((ch=fgetc(fp))!=-1)
num++;
printf("%d\n",num);
fclose(fp);
}
用fgets方法
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *fp;
char str[100] = {0};
int t = 0;
if ((fp=fopen("zi.tex","r"))==NULL)
{
printf("Can' t open the zi.tex\n");
return -1;
}
if((fgets(str,100,fp)) == NULL)
{
printf("fgets fail\n");
return -1;
//puts(str);
//t++;
}
while(str[t] != 10)
t++;
t++;
printf("t = %d\n",t);
for(t = 0;t<100;t++)
printf("%d ",str[t]);
fclose(fp);
return 0;
}
用fread方法
#include <stdio.h>
int main()
{
FILE *fp;
char ch[100];
size_t num=0;
fp=fopen("zi.tex","r");
num = fread(ch, sizeof(char),sizeof(ch), fp);
printf("num = %d",num);
return 0;
}
用read方法
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int net,net1,net2,t;
char buf[100] = {0};
net = open("zi.tex",O_RDWR,0777);
if(net < 0)
{
printf("open fail\n");
return -1;
}
//lseek(net,0,2);
net1 = read(net,buf,100);
if(net1 < 0)
{
printf("read fail\n");
return -1;
}
printf("net1 = %d\n",net1);
printf("buf = %s\n",buf);
close(net);
return 0;
}
另外一些方法
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int fd_t;
FILE *fd;
struct stat buf;
//======== low level ============================================
fd_t = open(argv[1], O_RDWR, 0666);
if (fd_t < 0)
{
printf("fail to open the file\n");
exit(1);
}
printf("size1 = %d\n", (int)lseek(fd_t, 0L, SEEK_END));//返回指针
if (close(fd_t) == -1)
{
printf("fail to close the file\n");
exit(1);
}
//======= standard ==============================================
fd = fopen(argv[1], "r");
if (fd == NULL)
{
printf("fail to fopen the file\n");
exit(1);
}
fseek(fd, 0L, SEEK_END);//指向末尾
printf("size2 = %ld\n", ftell(fd));//
if (fclose(fd) == EOF)
{
printf("fail to fclose the file\n");
exit(1);
}
//==============================================================
if (stat(argv[1], &buf) != 0)//读取文件属性
{
printf("stat fail\n");
exit(1);
}
printf("size3 = %d\n", (int)buf.st_size);
return 0;
}
注意:用fgetc等,是把流指就到了最后,再给到fread(buf,sizeof(char),num,fp);就会读取不到。
而ftell和fseek结合一起来用的话,就可以让指针回到首地址,然后给fread用。