【发布时间】:2021-07-22 18:06:00
【问题描述】:
我在运行代码之前创建的 .txt 文件如下所示:
/*
I am Jason and I love horses hahaha/n
This is amazing, How much I love horses, I think I am in love/n
how many people love horses like I do?/n/n
this is quite a horsed up paragraph
*/
//I also manually wrote '\0' character at the end of my string//
我想要这个程序的输出和上面一样,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *filepointer;
int buck;
int counter=1 ;
filepointer = fopen("inoutproj.txt","r");
while(buck=fgetc(filepointer),buck!=EOF)
{
if(buck=='\n')
{
++counter;
}
printf("%c",fgetc(filepointer));
}
printf("\nThere are %d lines in the text file\n\n",counter);
counter=1;
rewind(filepointer);
for(buck=fgetc(filepointer);buck<175;++buck)
{
if(fgetc(filepointer)=='\n')
{
++counter;
}
printf("%c",fgetc(filepointer));
}
printf("\nThere are %d lines in the text file\n",counter);
fclose(filepointer);
return 0;
输出如下:
mJsnadIlv osshhh
Ti saaig o uhIlv oss hn mi oe o aypol oehre ieId?
hsi ut osdu aarp�
There are 3 lines in the text file
a ao n oehre aaa hsi mzn,Hwmc oehre,ItikIa nlv
hwmn epelv osslk o
ti sqieahre pprgah���������������
文本文件有3行
如您所见,我用fgetc 尝试了两种不同的方法(While 循环和 for 循环),但输出仍然出现问题。我已经阅读了一些存档的 Macbook Pro 文档,其中循环正在从输入流中读取推回的输入,而且它似乎也一直在为我的代码执行此操作(或者我可能错了)。
谁能告诉我我编写的代码有什么问题以及为什么我的计算机没有按我的意愿输出 .txt 文件?
我目前在 VSCode 上运行 Cygwin GCC。
我的系统是 2019 年的 Macbook Pro 16
【问题讨论】:
-
'\0' 字符最后通过 fputs 使用另一个程序写为 \0。
-
数字 175 也来自运行 fseek 和 ftell。为了弄清楚如何使用 for 循环,我决定运行: fseek(filepointer,0,SEEK_END); printf("%ld",ftell(filepointer));找出我的文件末尾的数值。我不确定这个数字是否是我想要的。