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 w开发者_开发知识库ord;
}
int main() {
FILE *f;
f = fopen("testppm.ppm", "r");
char *word;
word = nextWord(f);
printf("%s",word);
}
In your nextWord
function, you never initialize the local variable word
to point at anything, so when you try to write to the pointed-at memory with strcat
, 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.
Or you can also use the fscanf function in your while loop.
char *nextWord(FILE *stream) {
char *buffer[124], *word;
int previous_size = 0;
while(!feof(!stream)){
int n = fscanf(file, "%s", buffer);
if(word == NULL){
word = malloc(sizeof(char)*n)
} else {
realloc(word, n + previous_size);
}
strncat(word, buffer, strlen(buffer) - 1);
previous_size = n;
}
return word;
}
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
精彩评论