簡體   English   中英

使用C系統調用修改文件

[英]Modifying a file using C System Calls

我想使用C系統調用來修改文件中的特定字節。 我對open(),read()和write()系統調用有一些了解。

說我要修改文件中的第1024個字節,而文件有2048個字節。 因此,我可以使用read()將1024個字節讀出到字符數組中,並更改所需的字節。

現在,當我將修改后的字符數組寫回文件時,文件的其余部分是否保持不變? 關於這一材料的學習材料尚不清楚。 請幫助我理解這一點。

您可以通過<stdio.h>的標准流輕松地進行此操作:

#include <stdio.h>
#include <ctype.h>

/* uppercase letter at offset 1024 */
FILE *fp = fopen("filename", "r+b");
if (fp) {
    fseek(fp, 1024L, SEEK_SET);
    int c = getc(fp);
    if (c != EOF) {
        fseek(fp, 1024L, SEEK_SET);
        putc(toupper((unsigned char)c), fp);
    }
    fclose(fp);
}

如果可以訪問Posix API,則可以直接使用系統調用,但是請注意,在某些情況下, write()可能會提前返回。 僅寫入單個字節應該不是問題,但是如果您寫入更改大塊文件,則可能會成為問題。 流接口更易於使用。 這是Posix代碼:

#include <unistd.h>
#include <ctype.h>

/* uppercase letter at offset 1024 */
unsigned char uc;
int hd = open("filename", O_RDWR | O_BINARY);
if (hd >= 0) {
    lseek(hd, 1024L, SEEK_SET);
    if (read(hd, &uc, 1) == 1) {
        lseek(hd, -1L, SEEK_CUR);
        uc = toupper(uc);
        write(hd, &uc, 1);
    }
    close(hd);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM