如何使用 C 中的 stdio.h 逐字读取文件?
我是 C 语言的新手,如果没有分段错误,我无法完全理解它。
到目前为止我的想法是:
#include<stdio.h>
#include<string.h>
char *nextWord(FILE *stream) {
char *word;
char c;
while ( (c = (char)fgetc(stream)) != ' ' && c != '\n' && c != '\0') {
strcat(word, &c);
}
return word;
}
int main() {
FILE *f;
f = fopen("testppm.ppm", "r");
char *word;
word = nextWord(f);
printf("%s",word);
}
I'm new to C and I can't quite get it without a segmentation fault.
Here's my idea so far:
#include<stdio.h>
#include<string.h>
char *nextWord(FILE *stream) {
char *word;
char c;
while ( (c = (char)fgetc(stream)) != ' ' && c != '\n' && c != '\0') {
strcat(word, &c);
}
return word;
}
int main() {
FILE *f;
f = fopen("testppm.ppm", "r");
char *word;
word = nextWord(f);
printf("%s",word);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
nextWord
函数中,您永远不会初始化局部变量word
来指向任何内容,因此当您尝试使用strcat,你会得到一个段错误。
您需要分配内存来存储您要读取的单词。问题是,您不知道该单词有多大,因此您不知道要分配多少空间。有多种可能的方法:
在读取单词时使用堆栈上的(大)固定大小缓冲区来保存单词,然后在返回单词时将其复制到适当大小的 malloc 区域。如果您遇到对于固定大小缓冲区来说太大的单词,将会出现问题。
分配一个小块来读取单词,并跟踪读取字符时使用了多少。当块已满时,将其重新分配为更大的块。
In your
nextWord
function, you never initialize the local variableword
to point at anything, so when you try to write to the pointed-at memory withstrcat
, you get a segfault.You need to allocate memory to store the word that you are going to read. The problem is, you don't know how big that word will be, so you don't know how much space to allocate. There are a number of possible approaches:
Use a (large) fixed size buffer on the stack to hold the word as you read it, then copy it to a malloc'd area of the appropriate size when you return it. There will be problems if you encounter a word that is too big for your fixed size buffer.
allocate a small block to read the word into, and keep track of how much is used as you read characters. When the block is full, realloc it to be bigger.
或者您也可以在 while 循环中使用 fscanf 函数。
一点解释。函数fscanf返回读取的字符数。所以我做的第一件事就是保存该值。如果 word 为 NULL,则使用字符数分配它,否则使用 previous_size 变量分配单词。
不要忘记刷新 buffer 变量
Or you can also use the fscanf function in your while loop.
A little explanation. The function fscanf returns the number of characters read. So the first thing i do is to save that value. If word is NULL you allocate it with the number of character otherwise you allocate word with the previous_size variable.
Don't forget to flush the buffer variable