int main()
{
// create a file
const string f = "./mumble.txt";
file_write(f,"Many mumbling mice",0);
file_append(f,"\nAre making merry music in the moonlight!",0);
file_append(f,"\nMighty nice!",0);
// check file length
long l = file_length(f), l2 = 0;
printf("\nlength: %d",l);
// allocate memory for reading the file into a string
char* str = malloc(l+1);
memset(str,0,l+1);
// fill the string with data and check how much data was copied
l2 = file_read(f,str,l+1);
printf("\nlength2: %d",l2);
// let's see where the newline characters are
int i = 0;
for(i = 0; i<l; i++)
{
if(str[i]=='\n') printf("\ni: %d, found newline!",i);
}
// let's print the string
printf("\n%s",str);
// let's find the last newline character (if not found, zero)
for(i = l-1; i>0; i--)
{
if(str[i]=='\n') {break;}
}
// point to the last part of the string by offsetting the pointer
char* lastline = str + i;
printf("%s",lastline);
// okay, now let's alter the original string to convert it into the first line only.
// Remember, a string is all data before a null character.
for(i=0; i<l; i++)
{
if(str[i]=='\n') {str[i]=0;break;}
}
// let's print the altered string (first line)
printf("\n%s",str);
// always free memory after using malloc
free(str);
return 0;
}