我正在尝试修改文件的大小。我正在与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: %sn", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %fn", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %cn", 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("%ldn",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("Beginn");
dummy_file();
print_size();
// truncate_file();
print_size();
printf("Endn");
return 0;
}
输出看起来像这样:
开始 80 40 结束
文件已更改为40个字节,但内容有很多空值。
我做错了什么?是否可以在维护其内容的同时截断文件?
在w
模式下使用fopen
打开文件时,您将文件截断为零长度。之后,当您运行ftruncate
时,它将用