I am writing a program to make a copy of a file (binary or text) in c. The first thing i need to do is read the file, after doing some research i found the fgets()
function.
However i found out that fgets() is deprecated and also according to a comment in that post fgets()
will not stop when it encounters NUL
:
null bytes do not belong in text files.
fgets() was designed to work with text files:
using fgets() with files of binary data is not recommended
fgets()
seems incomplete for reading binary/text files line by line unless certain hacky and inelegant lines are added when reading.
So my question is, how can i safely and reliably read a binary/text file line by line?
CodePudding user response:
I am writing a program to make a copy of a file (binary or text) in c.
Use fwrite
and fread
.
Simple copy function (you need to open files before calling it)
#define READBUFFSIZE (64*1024)
int copyFile(FILE *source, FILE *dest)
{
void *buff = malloc(READBUFFSIZE);
long length;
int result = 0;
if(!source || !dest || !buff || fseek(source, 0, SEEK_END)) {result = -1; goto cleanup_exit;}
length = ftell(source);
if(fseek(source, 0, SEEK_SET)) {result = -1; goto cleanup_exit;}
while(length)
{
long chunk = length >= READBUFFSIZE ? READBUFFSIZE : length;
if(fread(buff, 1, chunk, source) == -1) {result = -1; goto cleanup_exit;}
if(fwrite(buff, 1, chunk, dest) == chunk) {result = -1; goto cleanup_exit;}
length -= chunk;
}
cleanup_exit:
free(buff);
return result;
}
So my question is, how can i safely and reliably read a binary/text file line by line?
Binary files do not have lines - so you cant read them line by line.
Text files - use fgets
#define MAXLLINE 256
int main(int argc, char **argv)
{
char buff[MAXLINE]
if(argc >= 2)
{
FILE *fi = fopen(argv[1], "r");
if(fi)
{
size_t line = 0;
while(fgets(buff, MAXLINE, fi))
{
printf("[%zu] %s", line, buff);
}
}
else
{
/* error handling */
}
}
}
CodePudding user response:
Try creating a file pointer which is placed at the starting of the file and the file pointer is incremented so it can read each character and print it on console using a while loop until fileptr gets EOF.
It can implemented as:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* ptr;
char ch;
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
printf("content of this file are \n");
do {
ch = fgetc(ptr);
printf("%c", ch);
} while (ch != EOF);
fclose(ptr);
return 0;
}