我想从用户那里获取输入,然后将该输入保存到文件中。在下面的代码中,如果我删除我的while循环,则会附加该文件,但我希望此循环,以便用户可以输入最多500个字符的数据。
int main()
{
char Buffer1[5];
FILE *ot;
fopen_s(&ot, "D:\export1.txt", "a+");
fseek(ot, 0L, SEEK_END);
int sz = ftell(ot);
printf("Enter Data.n");
while (sz<500) {
for (int i = 0; i < 5; i++) {
scanf_s("%c", &Buffer1[i]);
}
// write data to file
for (int i = 0; i < 5; i++) {
fputc(Buffer1[i], ot);
}
sz = ftell(ot);
}
fclose(ot);
_gettch();
return 0;
}
仅当用户准确附加总共生成 500 字节所需的字节量时,此实现才有效。
首先检查文件大小,然后让用户输入最多 500 个文件大小字符,然后才将用户输入附加到文件中可能更容易。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <conio.h>
#define ARRAY_LIMIT 10
int main()
{
char array[ARRAY_LIMIT];
int i = 0;
FILE *ot;
fopen_s(&ot, "export1.txt", "a+");
fseek(ot, 0L, SEEK_END);
int sz = ftell(ot);
printf("Enter Data.n");
while (sz < 500)
{
while (i < ARRAY_LIMIT)
{
array[i] = getch();
printf("%c", array[i++]);
}
i = 0;
fwrite(array, sizeof(array), 1, ot);
sz = ftell(ot);
//be on the safe side...
if (sz != 500 && 500 - sz < ARRAY_LIMIT)
i = ARRAY_LIMIT - (500 - sz);
}
fclose(ot);
return 0;
}