【发布时间】:2021-08-17 17:44:27
【问题描述】:
我正在尝试这样做,以便您可以编写多行消息,并将其存储在您选择的文件中,然后输入 ` 完成,但是当我在顶部执行此操作时,会打印一个空白行。我怎样才能防止这种情况发生?
#include <stdio.h>
char filename[BUFSIZ];
char input[BUFSIZ];
FILE *file;
int main() {
printf("What do you want to name the file?\n");
scanf("%s", filename);
printf("Enter the contents. Once you are done enter `\n");
scanf("%[^`]s", input);
file = fopen(filename, "w");
fprintf(file, "%s", input);
fclose(file);
}
【问题讨论】:
-
%[]转换说明符不会跳过空格,因此它包含前一个scanf留下的换行符。在%[]转换说明符之后也不需要s。要修复它,请删除s,并在%之前放置一个空格。 -
或者更好的是,使用
fgets()或POSIXgetline()函数一次读取一行,这样您就不必担心缓冲区溢出。 -
至少在
BUFSIZ上你有8192字符在Linux 和512在Windows 上,例如对于 Linux glibc/libio/stdio.h - #define BUFSIZ 8192
标签: c file-io fopen stdio fclose