[英]How do I make the file pointer point at the very start of the file?
我在将文件指针设置为文件的开头时遇到了问题,以便在已经写入一些文本之后首先写入一些内容。
我试过 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() 中的数字,而不是我输入的内容。
这里的写作模式应该是w+
:
err = fopen_s(&maspass, "Master_Password.txt", "a" /* w+ */);
在这里,您应该关闭文件,然后将其删除:
if (count == 0)
{
/*fclose_s(maspass);*/
remove("Master_Password.txt");
printf("Master Password cannot be empty");
exit(0);
}
您应该保持文件描述符打开并将其传递给master_globalprint
,而不是这样做:
fclose(maspass);
master_globalprint(count);
/* master_globalprint(count, maspass);
* fclose(maspass); */
然后继续重用打开的文件描述符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.