C语言文件指针的使用...long file_size2(char * filename)

来源:互联网 发布:淘宝首页排版技巧 编辑:程序博客网 时间:2024/05/07 18:35


#include <ctype.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>int main(int argc, const char * argv[]){FILE * fp = NULL;// "w" 写 , 如果文件不存在, 可创建.fp = fopen("/Users/stone/Desktop/c.txt", "r+");char s = 'c';if (fp != NULL) {printf("open file success\n");fputc(s, fp);}else {printf("open file failed\n");printf("Press any key to exit\n");getchar();// #include <stdlib.h> 要导入, 不然有警告 隐式声明, 看着不爽exit(1);}//int a = fgetc(fp); "r+" 可以读写 为什么 fgetc 读取错误呢??? a = 127//printf("%c\n", toascii(a));fclose(fp);//********* 读取字符 *************** stone ***FILE * ff = fopen("/Users/stone/Desktop/c.txt", "r");int ch = fgetc(ff);// #include <ctype.h> 才能用 toasciiprintf("%c\n", toascii(ch)); // 也可以直接写 char ch2 = ch & 0x7F (因为ascii只有 0~127)// 0111 1111 & 0110 0011 = 0110 0011// putc(ch, ff);fclose(ff);//******* 写入一个字符串 ***************** stone ***FILE * fw = fopen("/Users/stone/Desktop/d.txt", "w");char str[] = "i love Chian !";/*     char 占一个字节     int 占四个字节     当int变量值 处于 -128到127之间时,int char可以直接互相赋值!     */for (int i = 0; i < strlen(str); i++) {fputc(str[i], fw);}fclose(fw);//******** 读取字符串 **************** stone ***FILE * fd = fopen("/Users/stone/Desktop/d.txt", "r");char tt[100];int i = 0;char cc = fgetc(fd);while (cc != EOF) {tt[i++] = cc;putchar(cc);cc = fgetc(fd);}printf("\n");printf("%s\n", tt);fclose(fd);//******* 获取文件的大小 ***************** stone ***long file_size2(char * filename);long count = file_size2("/Users/stone/Desktop/d.txt");printf("%ld\n", count);return 0;}long file_size2(char * filename){struct stat statbuf;stat(filename, &statbuf);long size = statbuf.st_size;return size;}


0 0
原创粉丝点击