read line

B

Bob Then

Is there any way to read a single at a time in from file I have a file with
variable length strings with diffrent amounts of words on each line.
 
W

Walter Roberson

Is there any way to read a single at a time in from file I have a file with
variable length strings with diffrent amounts of words on each line.

fgets() if there is a maximum string length.

If you don't want to set a maximum string length but want
the entire line returned anyhow (via dynamically allocated
memory), then there is no library routine that I can think of
for that.
 
A

Al Bowers

Bob said:
Is there any way to read a single at a time in from file I have a file with
variable length strings with diffrent amounts of words on each line.

You can write a function to dynamically allocate storage
(using function realloc) as you need it. Function fgetline
below allocates in blocks of 16 as you read the stream with
function fgetc. The example uses the stdin stream but
it could be used for reading a line in a file.

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

#define BLOCK 16

char *fgetline(FILE *fp)
{
char *s, *tmp;
size_t count;
int ch;

for(count = 0, s = NULL;
(ch = fgetc(fp)) != EOF && ch != '\n';count++)
{
if(count%BLOCK == 0)
{
tmp = realloc(s,count+BLOCK+1);
if(tmp == NULL)
{
free(s);
return NULL;
}
s = tmp;
}
s[count] = ch;
}
if(s) s[count] = '\0';
return s;
}

int main(void)
{
char *s;

printf("Enter a line of text: ");
fflush(stdout);
s = fgetline(stdin);
if(s) printf("You entered \"%s\"\n",s);
free(s);
return 0;
}
 
P

pete

Bob said:
Is there any way to read a single at a time in
from file I have a file with
variable length strings with diffrent amounts of words on each line.

If the situation is one where you have a known maximum line length
then you can do it this way:


#define LINE_LEN 63
#define str(x) # x
#define xstr(x) str(x)

int rc;
char array[LINE_LEN + 1];
FILE *fd ;
char *fn = "file.txt";

fd = fopen(fn, "r");
if (fd == NULL) {
fprintf(stderr, "\nfopen() problem with \"%s\"\n", fn);
exit(EXIT_FAILURE);
}

rc = fscanf(fd, "%" xstr(LINE_LEN) "[^\n]%*[^\n]", line);
if (!feof(fd)) {
getc(fd);
}

If rc equals 1, then a line has been converted to a string in array.

If the file line has more than LENGTH bytes,
the extra ones are discarded.

If rc equals 0, there was only a newline character in the file line
and no conversion was done.
If rc equals EOF, you've reached the end of the file.No conversion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top