getdelim - Linux
Overview
getdelim reads a line from a stream, delimited by a specified character. It is commonly used to read data from files or streams efficiently by delimiting the data into specific units or lines.
Syntax
getdelim(char **lineptr, size_t *n, int delimiter, FILE *stream)
Options/Flags
| Option | Description | Default Value |
|—|—|—|
| lineptr | Pointer to a character array that stores the read line | NULL |
| n | Pointer to an integer specifying the size of the character array | NULL |
| delimiter | Character that delimits the line | ‘\n’ |
| stream | File or stream to read from | stdin |
Examples
Example 1: Reading a line from a file
char *line = NULL;
size_t len = 0;
FILE *fp = fopen("test.txt", "r");
while (getdelim(&line, &len, '\n', fp) != -1) {
printf("%s", line);
}
fclose(fp);
Example 2: Reading CSV data with comma delimiter
char *line = NULL;
size_t len = 0;
FILE *fp = fopen("data.csv", "r");
while (getdelim(&line, &len, ',', fp) != -1) {
// Process each CSV field
}
fclose(fp);
Common Issues
- Invalid lineptr or n: Ensure
lineptr
points to a valid character array andn
is a valid integer pointer before calling getdelim. - EOF encountered: getdelim returns -1 when the end of the stream is reached. Check the return value to detect end-of-file.
- Buffer overflow: If
n
is too small, the entire line may not fit into the character array. Increase the size of the character array or reallocate it using realloc().
Integration
Example 3: Reading data and processing it with another command
getdelim(&line, &len, '\n', stdin) | grep "pattern"