K
K
kate2018-08-27 15:05:32
C++ / C#
kate, 2018-08-27 15:05:32

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!

and now I'm reading, but only "20" is displayed, why is that?
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

2 answer(s)
C
CityCat4, 2018-08-27
@CityCat4

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);

The output is an array data with file data.
Look for a newline ('\n') and rearrange the pointer FOR it (if you need to convert a number into a digit, then after rearranging to the newline place, write '\0' and use atoi() - the output is the length of the string that goes as a control, so as not to accidentally jump out on SIGSEGV.
Then, from the new position of the pointer, a cycle along the length of the string with a search in the substitution table.
Damn it ... after all, my mother swore that I would not prompt ...

R
Roman Mirilaczvili, 2018-08-27
@2ord

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 question

Ask a Question

731 491 924 answers to any question