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;
}
You could add these two lines after the line
last = lastline("data.txt");. The reasonNULLis printed, is because you are printing the result of the functionlastline(). This function will returnNULLon failure.