Reputation: 3162
I am trying to implement some code to pick out the last line of a text file, and am currently using this example, but I cannot figure how to prevent the code from printing out "(null)" when it cannot find the file, at the moment when it cannot find the file, it will print out "file cannot open at last line: no such file or directory" then it will print the null thing below, and for this particular application i would rather that it just print out the "file cannot open" part, but not print out the null part, if anyone could point me in the right direction for this I would really appreciate it, thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef max
#define max(a, b) ((a)>(b))? (a) : (b)
#endif
long GetFileSize(FILE *fp){
long fsize = 0;
fseek(fp,0,SEEK_END);
fsize = ftell(fp);
fseek(fp,0,SEEK_SET);//reset stream position!!
return fsize;
}
char *lastline(char *filepath){
FILE *fp;
char buff[4096+1];
int size,i;
long fsize;
if(NULL==(fp=fopen(filepath, "r"))){
perror("file cannot open at lastline");
return NULL;
}
fsize= -1L*GetFileSize(fp);
if(size=fseek(fp, max(fsize, -4096L), SEEK_END)){
perror("cannot seek");
exit(0);
}
size=fread(buff, sizeof(char), 4096, fp);
fclose(fp);
buff[size] = '\0';
i=size-1;
if(buff[i]=='\n'){
buff[i] = '\0';
}
while(i >=0 && buff[i] != '\n')
--i;
++i;
return strdup(&buff[i]);
}
int main(void){
char *last;
last = lastline("data.txt");
printf("\"%s\"\n", last);
free(last);
return 0;
}
Upvotes: 0
Views: 101
Reputation: 121387
You should check the return value of fread
to check whether it was successful. If fread
fails then errorno
will be set and your variable size
won't the number of chars read. Hence, your subsequent use of the variable buff
:
buff[size] = '\0';
i=size-1;
if(buff[i]=='\n'){
buff[i] = '\0';
}
could produce unexpected results. So is the strdup(buff[i])
which is returned from the function to main
.
Upvotes: 1
Reputation: 96258
It's coming from here: printf("\"%s\"\n", last);
if (last) {
printf("\"%s\"\n", last);
free(last);
}
Upvotes: 1
Reputation: 23033
You could add these two lines after the line last = lastline("data.txt");
. The reason NULL
is printed, is because you are printing the result of the function lastline()
. This function will return NULL
on failure.
if( last != NULL )
printf( "\"%s\"\n", last );
Upvotes: 1