【发布时间】:2019-12-09 04:02:19
【问题描述】:
我无法将文件指针设置为文件的开头,以便在已经写入一些文本之后首先写入一些内容。
我尝试过 rewind()、fseek()、以“r+”和“a+”模式打开文件,似乎没有任何效果。
这是该程序的一个小游戏:
#include<stdio.h>
#include<stdlib.h>
void master_globalprint(int lim)
{
int i = 0;
FILE* maspass;
errno_t err;
err = fopen_s(&maspass, "Master_Password.txt", "r+");
if (err != 0)
{
printf("Error opening Master_Password.txt");
exit(0);
}
rewind(maspass);
printf("Pointing to %ld", ftell(maspass));
while (i < lim)
{
fprintf(maspass, "%d", i); //Writing the array infront of the encrypted code
i++;
}
fclose(maspass);
}
void master_create() //To Create a Master Password
{
int count = 0;
char pass;
FILE* maspass;
errno_t err;
err = fopen_s(&maspass, "Master_Password.txt", "a");
if (err != 0)
{
printf("Error creating Master_Password.txt");
exit(0);
}
printf(" Enter Master Password : ");
while ((pass = getchar()) != EOF && pass != '\n')
{
count++;
fprintf(maspass, "%c", pass); //The characters are then printed one by one
}
if (count == 0)
{
remove("Master_Password.txt");
printf("Master Password cannot be empty");
exit(0);
}
fprintf(maspass, "%c", (count + 33)); //To put the amount of letters into file, forwarded by 33 to reach a certain ASCII threshold and converted to char
fprintf(maspass, "\n");
fclose(maspass);
master_globalprint(count);
}
void main()
{
master_create();
}
上述函数工作并打印正确的值,除了 master_globalprint 函数从最后一个函数停止的位置开始打印。
是因为我必须使用命令行参数来完成任务吗?如果是这样,我是否可以将命令行参数设置为默认执行,这样如果代码被分发,用户就不必费心了?
编辑:在可重现的代码示例中添加。当我在第 31 行输入“a”时,它只打印我输入的内容,而不是 master_globalprint() 中的数字。如果我输入“w”,它只会打印 master_globalprint() 中的数字,而不是我输入的内容。
【问题讨论】:
-
"a+"模式到fopen()的意思是“所有写入都附加在文件末尾”,无论写入前文件中的当前位置如何。如果您不想附加所有内容,请不要使用a;请改用"r+"或"w+"模式。即使您使用"r+"或"w+"模式,您也无法在文件中已有的内容之前插入数据;您所能做的就是覆盖已经存在的内容。 -
即使你使用
"r+"或"w+"模式,你也无法在文件已经存在的内容之前插入数据;您所能做的就是覆盖已经存在的内容。请参阅Inserting data into the middle of a file 或Delete data from the middle of a file 了解更多信息。 -
离题了,但是像
fopen_s()这样的函数并不比fopen()这样的标准函数更安全,而且*_s()函数是微软实现的非标准函数且不可携带。 -
printf("error:...(几乎)总是一个错误。应该是fprintf(stderr, "error:... -
printf("Pointing to %d", ftell(maspass)); //prints 0 every time是未定义的行为,因为ftell()返回long int,而不是int。您需要使用%ld。
标签: c file-handling