gpt4 book ai didi

C 文件顶部新行

转载 作者:行者123 更新时间:2023-11-30 17:40:19 25 4
gpt4 key购买 nike

#include  <stdio.h>
#include <stdlib.h>

#define MAX_LENGTH 100

FILE * openFile( char * mode )
{
FILE *file;
char name[50];

printf("Enter a name of a file:\n");
scanf("%49s", name);

file = fopen(name, mode);

if( ! file )
{
printf("Error opening the file.\n");
exit( 1 );
}

return file;
}

int main ( int argc, char * argv [] )
{
char row[MAX_LENGTH];

printf("Output file:\n");
FILE *output = openFile("w");

while( fgets(row, MAX_LENGTH, stdin) ) /*Stops with EOF (ctrl+d - Unix, ctrl+z - Windows)*/
{
fputs(row, output);
}

fclose(output);

return 0;
}

您好,上面的代码应该从标准输入中获取字符串并将其写入文件。

我知道当我按 Enter 时,fgets 将读取新行。我对此很满意。

问题是我创建的文件顶部也有一个换行符,但我不知道为什么。

如果有任何解释,我将不胜感激。谢谢

最佳答案

您可以采取的解决方法是将指针移动到文件的开头。

void rewind(FILE *stream);

它相当于

fseek(stream, 0L, SEEK_SET);

您可以查看此帖子:Does fseek() move the file pointer to the beginning of the file if it was opened in "a+b" mode?

关于C 文件顶部新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com