creat函式
#include #include //這三個creat函式要用的標頭檔案
#include #include #include //包含exit
#include int main()
return 0;
}
open函式和read函式
#include #include #include #include #include #include #include int main()
;#if 0
fd = open("hello.c", o_rdwr); //以讀寫方式開啟檔案
if(-1 == fd)
close(fd);
#endif
fd = open("hello.txt", o_rdwr | o_creat, s_irwxu);
if (-1 == fd)
ret = write(fd, buf, sizeof(buf));
if (-1 == ret)
lseek(fd, 0, seek_set);
memset(buf, 0, sizeof(buf));
ret = read(fd, buf, sizeof(buf));
if (-1 == ret)
printf("read from txt: %s\n", buf);
close(fd);
return 0;
}
使用open函式和read函式linux命令cp
#include #include #include #include #include #include int main(int argc, char *argv)
; if (argc != 3)
fp_from = open(argv[1], o_rdonly);
if (-1 == fp_from)
fp_to = open(argv[2], o_wronly | o_creat | o_excl, s_irwxu);
if (-1 == fp_to)
while ((ret = read(fp_from, buf, sizeof(buf) - 1)) >0)
memset(buf, 0, sizeof(buf));
}close(fp_from);
close(fp_to);
return 0;
}
fopen函式
#include #include #include int main()
; fp = fopen("hello.c", "a+"); //以讀和追加方式開啟hello.c,如果不存在則建立
if (null == fp)
ret = fseek(fp, 0, seek_set);
if (-1 == ret)
ret = fread(buf, 1, sizeof(buf), fp);
if (-1 == ret)
printf("read from txt : %s\n", buf);
memset(buf, 0, sizeof(buf));
scanf("%s", buf);
ret = fwrite(buf, 1, strlen(buf), fp);
if (-1 == ret)
fclose(fp);
return 0;
}
獲取檔案的大小
#include #include int main(int argc, char *argv)
fp = fopen(argv[1], "a");
fseek(fp, 0, seek_end);
int length = ftell(fp);
printf("the length is %d\n", length);
return 0;
}
將結構體成員寫入檔案
#include #include #include #include #include #include struct student
;typedef struct student stu;
int main()
; stu s2 = ;
int fd = open("student.txt", o_wronly | o_creat | o_excl, 0666);
if (-1 == fd)
int ret = write(fd, (void *)&s1, sizeof(s1));
if (-1 == ret)
ret = write(fd, (void *)&s2, sizeof(s2));
if (-1 == ret)
stu s;
fd = open("student.txt", o_rdonly);
if (-1 == fd)
while (1)
if (0 == ret)
printf("%s %d %c\n", s.name, s.age, s.***);
memset(&s, 0, sizeof(s));
}return 0;
}
linuxc程式設計 檔案操作 部分函式
標頭檔案 include 在centos6.0中只要此標頭檔案就可以 include incldue功能 開啟和建立檔案 建立乙個檔案描述符,其他的函式可以通過檔案描述符對指定檔案進行讀取與寫入的操作。函式原型 int open const char pathname,int flags int o...
Linux 檔案操作函式
底層檔案操作函式 includeint open const char pathname,int flags int open const char pathname,int flags,mode t mode 返回值 成功,返回檔案描述符 失敗,返回 1,失敗原因記錄在errno中 int clo...
Linux檔案操作函式
寫專案的時候,當我把實現linux的基本功能的 寫完之後,寫斷點續傳時,有點難度 我對lseek學的不好 send這個函式是不能傳整形值的只能傳字元型別 1 open int open const char filename,int flag,int mode 返回值 1 1 出錯 2 0 返回乙個...