I know it is a very basic thing, but I'm not very good at file handling in C.
I'm writing a custom error handler for something, and it needs to open a file, find a line by i开发者_StackOverflowts number, and save it in a char*.
Can someone suggest a way to do it?
Edit: What am I doing wrong? Sometimes it gets the right line, but sometimes it misses:
if (file_available)
{
char str_buf[81];
int counter = 0;
FILE *fp;
fp=fopen(error_filename, "r");
while (error_lineno != counter)
{
fgets(str_buf, 81, fp);
counter += 1;
}
php_printf(html_formats[5],"Line",str_buf);
fclose(fp);
}
If you have access to the GNU C library, you can use getline
:
FILE *f;
char *line = NULL;
size_t line_size = 0;
int i=0;
/* Open the file, or get access it to it however you will */
for(; i <= requestedLine; ++i) {
if ( getline(&line, &line_size, f) == -1 ) {
//error condition, log / bail
}
}
/* line now holds the line number you want, do whatever you want with it */
fclose(f);
if (line) {
/* guard against the empty file case */
free(line);
}
getline
will grab the full line for you and take care of most of the memory allocation issues. The first parameters is a pointer to a char*
buffer (as in a char**
-- a pointer to a pointer to the beginning char
of a buffer), and the second is the size of that buffer. If the buffer is not large enough, getline
will create a new buffer large enough to hold the line and clean up your old one (performs a realloc
). When the function returns, the first parameter will now point to the new buffer which contains the line, and the second parameter will also be updated to hold the new size of the buffer. The third parameter is simply the FILE*
object to read from. getline
will return a -1 on failure, which is why we log / bail in that case.
Note that when all is done you still need to free the buffer that getline
creates.
You could write a loop with fgets()
to read lines until you get to the one you want:
inputFile = fopen(filename, "r");
while (whichLine--)
{
fgets(buffer, sizeof buffer, inputFile);
}
fclose(inputFile);
Add error handling and further details to your taste.
精彩评论