如何在c中直接写入磁盘
How to write straight to disk in c
所以我正在尝试制作一个擦除驱动器的程序。经过一些研究,我发现所有设备都存储在 Ubuntu 中的 /dev/ 文件夹下。我尝试了以下...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *fp = fopen("/dev/sdb1", "w");
fwrite("[=10=]", 1, 1, fp);
fclose(fp);
return 0;
}
但是发现它返回了
Segmentation fault (core dumped)
这是为什么?我应该不能只写入磁盘吗?
您很可能没有打开 /dev/sdb1
的权限。在尝试使用它之前检查 fopen
(fp
) 的结果:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]){
FILE *fp = fopen("/dev/sdb1", "w");
if(fp == NULL){
fprintf(stderr, "Error opening /dev/sdb1: %s\n",
strerror(errno));
return EXIT_FAILURE;
}
/* Now you can use fp */
fwrite(0, 1, 1, fp);
fclose(fp);
return 0;
}
fopen
returns NULL
when opening failed, and puts the reason in the global* variable errno
. strerror
returns 该错误代码的描述性字符串。
您可能需要 运行 您的程序以 root 身份访问块设备。不用说,在这样做之前调试得很好,否则你可能会毁了你的系统(特别是如果你正在搞直接磁盘访问)。
所以我正在尝试制作一个擦除驱动器的程序。经过一些研究,我发现所有设备都存储在 Ubuntu 中的 /dev/ 文件夹下。我尝试了以下...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *fp = fopen("/dev/sdb1", "w");
fwrite("[=10=]", 1, 1, fp);
fclose(fp);
return 0;
}
但是发现它返回了
Segmentation fault (core dumped)
这是为什么?我应该不能只写入磁盘吗?
您很可能没有打开 /dev/sdb1
的权限。在尝试使用它之前检查 fopen
(fp
) 的结果:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]){
FILE *fp = fopen("/dev/sdb1", "w");
if(fp == NULL){
fprintf(stderr, "Error opening /dev/sdb1: %s\n",
strerror(errno));
return EXIT_FAILURE;
}
/* Now you can use fp */
fwrite(0, 1, 1, fp);
fclose(fp);
return 0;
}
fopen
returns NULL
when opening failed, and puts the reason in the global* variable errno
. strerror
returns 该错误代码的描述性字符串。
您可能需要 运行 您的程序以 root 身份访问块设备。不用说,在这样做之前调试得很好,否则你可能会毁了你的系统(特别是如果你正在搞直接磁盘访问)。