以下 C 程序创建指定长度的空文件。我已经在我本地的 Ubuntu 20.04 笔记本电脑上对此进行了测试,它可以工作。我现在在 Digital Ocean (Ubuntu 22.04) 的一个实例中运行它,但行“fclose(outfile);”抛出分段错误。在云中,我在 Docker 容器中运行它,但不在本地运行。
#include <stdio.h>
#include <string.h>
#include <errno.h>
size_t create_empty_file (char * out_fname, size_t file_size)
{
FILE *outfile;
char buf[1024];
outfile = fopen(out_fname, "wb+");
if (outfile == NULL) {
strcpy(buf, strerror(errno));
printf("%d --> %s\n", errno, buf); }
fseek(outfile, file_size, SEEK_SET);
if (errno != 0) {
strcpy(buf, strerror(errno));
printf("%d --> %s\n", errno, buf); }
fputc('\0', outfile);
if (errno != 0) {
strcpy(buf, strerror(errno));
printf("%d --> %s\n", errno, buf); }
fclose( outfile );
return 0;
}
文件确实被创建并且文件确实被关闭 - 我知道这一点,因为它显示文件大小为零,直到文件关闭,并且文件确实显示其 4GB 指定长度。
通常情况下,当文件指针为空时,fclose 会抛出段错误,但这里不是这种情况。它可以在我本地的笔记本电脑上运行。
以下是来自 GDB 的段错误详细信息:
程序接收信号SIGSEGV,分段错误。 __GI__IO_setb 中的 0x00007fe121321c70 (f=f@entry=0x145b210、b=b@entry=0x0、eb=eb@entry=0x0、a=a@entry=0)位于 ./libio/genops.c:338 第338章 ./libio/genops.c:没有这样的文件或目录。
感谢您对此的任何帮助。
您没有正确处理错误,这可能会导致内存损坏,从而破坏
fclose(...)
。该错误很可能出在您的程序中,而不是在 fclose(...)
中。
以下是如何正确处理错误:
#include <stdio.h>
#include <string.h>
#include <errno.h>
/* Returns 0 on success, -1 on error. Sets errno to a useless value. */
int create_empty_file (char * out_fname, size_t file_size) {
FILE *outfile = fopen(out_fname, "wb+");
if (outfile == NULL) {
fprintf(stderr, "fopen: %d: %s\n", errno, strerror(errno));
return -1;
}
if (file_size != 0) {
if (fseek(outfile, file_size - 1, SEEK_SET) != 0) {
fprintf(stderr, "fopen: %d: %s\n", errno, strerror(errno));
fclose(outfile);
return -1;
}
fputc('\0', outfile);
if (ferror(outfile) || fflush(outfile) != 0) {
fprintf(stderr, "fputc\n");
fclose(outfile);
return -1;
}
}
fclose(outfile);
return 0;
}