Answer the question
In order to leave comments, you need to log in
How to work with text files?
A text file is given, in which the number of characters is stored on the first line, and the number of characters on the second line.
and replace vowels with spaces in the output, but that doesn't matter now.
how to count 2 lines from a file?
This is how I created the text file:
20
Hello World!
char str[100];
FILE *file_ptr;
file_ptr = fopen("C:/c/file.txt", "r + a");
if (file_ptr != NULL)
{
fgets (str, 100, file_ptr);
fprintf(stdout, "%s\n", str);
}
Answer the question
In order to leave comments, you need to log in
Because the normal algorithm for working with small text files is as follows:
open a file for reading (man open - attention, not a stream fopen, but a simple open!)
get the file size from the directory contents element (man stat)
allocate memory the size of a file (man calloc)
read the entire file (man read)
close the file (man close)
and then parse the resulting buffer as you like up and down, not forgetting, of course, that you don’t need to spoil it :)
Well, or this way it will probably be clearer:
#define NUL 0
#define ERR -1
int i;
short int handle;
struct stat sb;
char *name="/tmp/testfile.txt";
char *data;
if ((handle = open(name, O_RDONLY)) < NUL)
return ERR;
stat(name, &sb);
data = (char *) сalloc(sb.st_size + 1);
i = read(handle, data, sb.st_size);
close(handle);
Because only the first line has been read from the file, but both lines need to be read.
In addition, at the end of the work with the file, you need to close the file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question