我正在撰寫一個程式來從一個檔案中讀取指定的資料片段并將其寫入第二個檔案的指定偏移量,但是我有一個問題。由于某種原因,該fwrite函式沒有寫入從第一個檔案讀取的資料。相反,它會在第二個檔案的偏移處寫入一個非列印字符(可能是空字符,idk)。這是代碼:
int main(int argc, char **args)
{
if (argc < 7)
{
print_usage(args[0]);
exit(EXIT_FAILURE);
}
else if (argc > 7)
{
printf("Too many parameters\n");
exit(EXIT_FAILURE);
}
if (geteuid() != 0)
{
printf("This program requires root privileges\n");
exit(EXIT_FAILURE);
}
unsigned long offset;
unsigned long size;
char *partpath;
char *filepath;
int c;
for (c = 0; c < argc; c )
{
char *arg = args[c];
if (strcmp(arg, "-o") == 0)
{
offset = strtoul(args[ c], NULL, 0);
continue;
}
if (strcmp(arg, "-s") == 0)
{
size = strtoul(args[ c], NULL, 0);
continue;
}
if (c == argc - 2)
partpath = args[c];
if (c == argc - 1)
filepath = args[c];
}
printf("offset: %lu (0x%lx)\nsize: %lu (0x%lx)\npartition: %s\nfile: %s\n", offset, offset, size, size, partpath, filepath);
flash_part(partpath, offset, filepath, size);
return 0;
}
void flash_part(const char *partition_path, unsigned long offset, const char *file_to_flash, unsigned long size)
{
log("Opening files...");
FILE *partition = fopen(partition_path, "r ");
FILE *flash_file = fopen(file_to_flash, "r");
log("Jumping to partition offset...");
// jump to partition offset
fseek(partition, offset, SEEK_SET);
// start flashing chunk by chunk
log("Start flashing...");
void *chk = calloc(1, sizeof(void*));
size_t count = read_chk(flash_file, chk);
printf("readed %d bytes\n", count);
write_chk(partition, chk, count);
free(chk);
while (count >= CHK_SIZE)
{
chk = calloc(1, sizeof(void*));
count = read_chk(flash_file, chk);
write_chk(partition, chk, count);
free(chk);
}
log("Partition flashed, closing files...");
fclose(partition);
fclose(flash_file);
}
size_t read_chk(FILE *file, void *out)
{
char *chk_data = calloc(CHK_SIZE, 1);
size_t readed = fread(chk_data, 1, CHK_SIZE, file);
out = chk_data;
return readed;
}
void write_chk(FILE *file, void *data, unsigned int size)
{
fwrite(data, 1, size, file);
}
它出什么問題了?
uj5u.com熱心網友回復:
你read_chk的徹底壞了。您接受來自用戶的指標,忽略它,分配一個完全不同的東西,填充它,替換收到的指標(而不是將資料復制到它指向的位置;分配給指標會更改該指標,而不是相同指標的副本呼叫者持有),所以從呼叫者的角度來看,什么也沒發生;它傳遞了一個指向零緩沖區的指標,您沒有在緩沖區中放入任何內容,因此它仍然具有原始零(“呼叫者”最終可能會注意到,當程式從read_chk'scalloc呼叫的漸進式記憶體泄漏中崩潰時,這些呼叫永遠不會freed,但這并不是真正有用的反饋)。
從本質上講,你的寫作沒有任何問題,它準確地寫出了你告訴它寫的所有零。
解決方案取決于CHK_SIZE; 如果與 相同sizeof(void*),則去掉chk_data直接傳給out它fread的位置。如果它更大,你做同樣的事情,但將呼叫者更改為callocusingCHK_SIZE而不是sizeof(void*). 無論哪種方式,read_chk更改看起來像:
size_t read_chk(FILE *file, void *out)
{
return fread(out, 1, CHK_SIZE, file);
}
將其留給呼叫者以提供CHK_SIZE要使用的緩沖區。呼叫者也可以完全跳過calloc;可以使用堆疊陣列char buf[CHK_SIZE];并消除動態分配和釋放的需要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462114.html
標籤:C
下一篇:分段錯誤C陣列和Malloc
