gpt4 book ai didi

c - ftruncate 无法与 msys2 一起正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:46 25 4
gpt4 key购买 nike

我正在尝试修改文件的大小。我正在使用 msys2。我的代码如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void dummy_file(){
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
}

void print_size(){
FILE *f = fopen("file.txt", "r");
long sz = 0;
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fseek(f, 0L, SEEK_END);
sz = ftell(f);
printf("%ld\n",sz);
fclose(f);
}

void truncate_file(){
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
ftruncate(fileno(f), 40);
fclose(f);
}

int main()
{
printf("Begin\n");
dummy_file();
print_size();
// truncate_file();
print_size();
printf("End\n");
return 0;
}

输出看起来像这样:

开始 80 40 结束

文件已更改为 40 字节,但内容为大量空值。

我做错了什么?有没有其他方法可以在保留文件内容的同时截断文件?

最佳答案

当您在 w 模式下使用 fopen 打开文件时,您会将文件截断为零长度。之后,当您运行 ftruncate 时,它将用 \0 填充文件以达到您指定的大小。

来自 fopen 手册页,

w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

您可以改为使用 r+ 模式打开它,该模式不会截断文件(如果存在)并允许写入。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void dummy_file(){
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
}

void print_size(){
FILE *f = fopen("file.txt", "r");
long sz = 0;
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fseek(f, 0L, SEEK_END);
sz = ftell(f);
printf("%ld\n",sz);
fclose(f);
}

void truncate_file(){
FILE *f = fopen("file.txt", "r+");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
ftruncate(fileno(f), 40);
fclose(f);
}

int main()
{
printf("Begin\n");
dummy_file();
print_size();
truncate_file();
print_size();
printf("End\n");
return 0;
}

只是在扩展代码时要考虑的旁注:如果不遵循某些步骤,混合文件描述符和 STD I/O 流可能会导致未定义的行为(有关更多信息,请参阅 this answer,它指向 this link) .

关于c - ftruncate 无法与 msys2 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48685185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com