Linux文件非讀寫操作

来源:http://www.cnblogs.com/xiaojiang1025/archive/2016/10/06/5933813.html
-Advertisement-
Play Games

access() fstat()、stat()、lstat() 獲取文件大小 1. fseek()把offset移到SEEK_END, 再用ftell()返迴文件的大小 2. lseek() , 返迴文件的大小 3.stat(), struct stat st; st.st_size的數值就是文件大 ...


access()

//檢查是否調用進程有Access這個文件的許可權,如果文件是一個符號鏈接,會將它解引用,成功返回0,失敗返回-1設errno
#include <unistd.h>
int access(const char *pathname, int mode);
/*mode(Bitwise Or) :
F_OK    //文件是否存在
R_OK    //文件是否存在且授予了該進程讀許可權
W_OK    //文件是否存在且授予了該進程寫許可權
X_OK    //文件是否存在且授予了該進程執行許可權
*/
if(0==access("./a.txt",F_OK))
    printf("file exists\n");
if(0==access("./a.txt",R_OK))
    printf("file exists and grants read permission\n");

fstat()、stat()、lstat()

//讀取文件狀態,fstat()從fd讀取,stat () i從pathname讀取,lstat()從pathname讀取,如果文件是符號鏈接,則返回符號鏈接本身的信息,而其他的函數會對鏈接解引用
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int fstat(int fd, struct stat *buf);
int stat (const char *pathname,     struct stat *buf);
int lstat(const char *pathname,     struct stat *buf);
/*
struct stat {
    dev_t   st_dev;         /* ID of device containing file */
    ino_t   st_ino;         /* inode number */
    mode_t  st_mode;        /* protection */                    //八進位usigned int o%
    nlink_t st_nlink;       /* number of hard links */
    uid_t   st_uid;         /* user ID of owner */
    gid_t   st_gid;         /* group ID of owner */
    dev_t   st_rdev;        /* device ID (if special file) */
    off_t   st_size;        /* total size, in bytes */          //ld%
    blksize_t   st_blksize; /* blocksize for filesystem I/O */
    blkcnt_t    st_blocks;  /* number of 512B blocks allocated */
    time_t  st_atime;       /* time of last access */   
    time_t  st_mtime;       /* time of last modification */     //ld%,秒
    time_t  st_ctime;       /* time of last status change */
};

一些POSIX巨集可以用來檢查文件類型
S_ISREG(m)      //is it a regular file?     //if yes, return 1
S_ISDIR(m)      //is it directory?
S_ISCHR(m)      //is it character device?
S_ISBLK(m)      //is it block device?
S_ISFIFO(m)     //is it FIFO (named pipe)?
S_ISLNK(m)      //is it symbolic link?      (Not in POSIX.1-1996.)
S_ISSOCK(m)     //is it socket?             (Not in POSIX.1-1996.)
*/

獲取文件大小

  1. fseek()把offset移到SEEK_END, 再用ftell()返迴文件的大小
  2. lseek() , 返迴文件的大小
    3.stat(), struct stat st; st.st_size的數值就是文件大小
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
    struct stat st={};
    int res=stat("./a.txt",&st);
    if(-1==res)
        printf("stat"),exit(-1);
    printf("st_mode=%o,st_size=%ld,st_mtime=%ld\n",st.st_mode,st.st_size,st.st_mtime);
    if(S_ISREG(st.st_mode))
        printf("Regular file\n");
    if(S_ISDIR(st.st_mode))
        printf("Dir file\n");
    printf("file prot:%o\n",st.st_mode&0777);
    printf("file size:%ld\n",st.st_size);
    printf("latest modify:%s",ctime(&st.st_mtime));
    struct tm* pt=localtime(&st.st_mtime);
    printf("latest modify:%d-%d-%d-%02d:%02d:%02d\n",
        1900+pt->tm_year,1+pt->tm_mon,pt->tm_mday,pt->tm_hour,pt->tm_min,pt->tm_sec);
                                //%02輸出2個字元寬度,不足兩位輸出0站位
    return 0;
}

chmod()、fchmod():

//更改文件的許可權,這兩個函數的唯一區別就是指定文件的方式不一樣,成功返回0,失敗返回-1,設errno
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
int fchmod(int fd, mode_t mode);

truncate()、ftruncate():

//截斷文件為指定大小,成功返回0,失敗返回-1設errno
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
/*
如果原大小  >  指定大小,多餘的文件數據被丟棄
如果原大小e  <  指定大小,文件被擴展,擴展的部分被填充為'\0'
*/
/*-----------------------
 * chmod(),truncate();
 * -------------------*/
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int res=chmod("a.txt",0600);
if(-1==res)
    perror("chmod"),exit(-1);

int res=truncate("a.txt",100);
if(-1==res)
    perror("truncate"),exit(-1);
/*------------------------------------------------------
ftruncate();mmap();結構體指針初始化
----------------------------------------------------*/
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/mman.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
    int id;
    char name[20];
    double salary;
}Emp;
int main(){
    int fd=open("./emp.dat",O_RDWR|O_TRUNC|O_CREAT,0664);
    if(-1==fd)
        perror("open"),exit(-1);
    printf("open success\n");
    int res=ftruncate(fd,3*sizeof(Emp));        //要用sizeof,且是Emp(類型)不是emp(對象)
    if(-1==res)
        perror("ftruncate"),exit(-1);
    
    void* pv=mmap(NULL,3*sizeof(Emp),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if((void*)-1==pv)
        perror("mmap"),exit(-1);

    Emp *pe=pv;
    pe[0].id=1001;strcpy(pe[0].name,"zhangfei");pe[0].salary=3000;
    pe[1].id=1002;strcpy(pe[1].name,"guanyu");pe[1].salary=3500;
    pe[2].id=1003;strcpy(pe[2].name,"liubei");pe[2].salary=4000;
//  *(pe+2)={1003,"liubei",4000};
//  pe+2->salary=4000;              //ATTENTION:    ->優先順序比+高, 所以一定要加()
    printf("map success\n");
    res=munmap(pv,3*sizeof(Emp));
    if(-1==res)
        perror("munmap"),exit(-1);
    printf("unmap success\n");
    res=close(fd);
    if(-1==res)
        perror("close"),exit(-1);
    printf("close success\n");
    return 0;
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 管道是Linux的十種文件類型之一,使用管道通信本質上還是以文件作為通信的媒介 有名管道+無名管道=管道 有名管道(FIFO文件):就是 有文件名的管道, 可以用於任意兩個進程間的通信 無名管道(pipe文件):就是沒有文件名的管道, 只能用於父子進程之間的通信 mkfifo 創建有名管道,管道不能 ...
  • Linux中, 系統為每個系統都維護了三種計時器,分別為: 真實計數器, 虛擬計時器以及實用計時器, 一般情況下都使用真實計時器 getitimer()/setitimer() which //具體的計時器類型 1. ITIMER_REAL :真實計時器 統計進程消耗的真實時間 通過定時產生SIGA ...
  • 信號本質上就是一個軟體中斷,它既可以作為兩個進程間的通信的方式, 更重要的是, 信號可以終止一個正常程式的執行, 通常被用於處理意外情況 , 信號是非同步的, 也就是進程並不知道信號何時會到達 $kill 9 3390 向PID為3390的進程發送編號為9的信號= 一個兩個進程間通信的方式之一 一共6 ...
  • 環境:虛擬機VMware10 首先瞭解幾個註意的地方: 一、分區類型: 1、主分區:最多只能有四個; 2、擴展分區:最多只能有一個,且主分區加上擴展分區最多只能有四個,擴展分區不能寫入數據,只能包含邏輯分區 3、邏輯分區:可以寫入數據和格式化 舉個例子如圖: 其中1、2、3為主分區,4為擴展分區,5 ...
  • 向一個/一些進程發送一個信號 $kill [ slL] [...] 指定發送的信號,可以使用名稱或者信號編號 列出當前系統的所有信號 ...
  • 概述 多進程代碼區模型(其他區參見copy on write): getpid()、getppid() getuid()、geteuid() getgid(),getegid() fork() include include if(0==pid){ int res=execl("./proc","p ...
  • ps
    查看當前終端所啟動的進程, 不加選項只查看當前終端的進程 ps aux 查看所有進程,ps aux是BSD syntax,ps aux是standard syntax, 但二者的意義完全不同= $man ps ps ef 以全格式的方式顯示所有進程(every)查看當前終端所啟動的進程, 不加選項只 ...
  • 本文首先從巨集觀的角度對進程間的通信方式之一,消息隊列進行闡述,然後以代碼實例對消息隊列進行更近一步的闡述,最後試著暢想消息隊列的潛在應用 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...