- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在使用这个可以读取文件的小函数时遇到了一些问题:
void ReadFile(char *name) {
FILE *fr;
int lenght, i;
fr = fopen(name, "r"); //Open the file reader
fseek(fr, 0, 2); //Set the pointer at the EOF
lenght = ftell(fr); //Read the ending position
printf("\nDEBUG lenght:%d\n", lenght);
fseek(fr, 0, 0); //Return at the beginning of the file
printf("File read:\n\n");
for (i = 1; i <= lenght; i++) {
printf("%c", getc(fr));
fseek(fr, i, 0);
}
fclose(fr);
}
这是它读取的文件:
qwerty
asdfgh
zxcvbn
但这是程序的输出:
DEBUG lenght:24
File read:
qwerty
asdfgh
zxcvbn
基本上就是在前面有一个"\n"的时候多读一个"\n"。
关于为什么代码不起作用的任何想法?
谢谢
最佳答案
如果您以文本模式打开文件(像您一样),则调用 fseek
可能只包含先前由 ftell
检索到的偏移值函数(参见,例如 cppreference/fseek ):
If the stream is open in text mode, the only supported values for offset are zero (which works with any origin) and a value returned by an earlier call to ftell on a stream associated with the same file (which only works with origin of SEEK_SET).
在你的for
-loop,但是,您正在传递 i
的值, 未被 ftell
检索到.
除此之外,您的 fseek
在循环中是多余的,如fgetc
无论如何向前移动读指针。所以for (i = 1; i <= lenght; i++) { printf("%c", getc(fr)); }
应该完成这项工作。
关于c - Getc 过度读取一个\n 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49865369/
我正在开发适用于 Wordpress 的 PSD,并面临着根据颜色过度对齐背景图像或相反的问题。 在桌面上一切都很好,但在移动设备上背景图像变小了(我使用了 background-size: 100%
在标准 Modelica 流体流量源中,通常指定流量或压力。例如,以下边界设置(P 表示压力边界,F 表示流量边界)通常会围绕管道组件: P - 管道 - P F - 管道 - P 但是,有时在同一侧
我正处于设计基于 Azure 的应用程序的早期阶段。考虑到我可能预期的需求的变化性,Azure 吸引我的地方之一是它的可扩展性。因此,我试图保持事物松散耦合,以便我可以在需要时添加实例。 我看到的关于
我与 Xcode 4 dot notation code sense problem 正好相反!点符号的代码完成不仅显示属性,还显示我的方法(在每个完成的左侧标记 P 或 M 分别指示它是属性还是方法
我是一名优秀的程序员,十分优秀!