The most compact way to count the number of lines in a file in C ++

What is the most compact way to calculate the number of lines of a file? I need this information to create / initialize a matrix data structure.

Later I need to view the file again and save the information inside the matrix.

Update: Based on Dave Gamble's. But why doesn't it compile? Please note that the file can be very large. Therefore, I try to avoid using a container to save memory.

#include <iostream>      
#include <vector>        
#include <fstream>       
#include <sstream>       
using namespace std;     


int main  ( int arg_count, char *arg_vec[] ) {
    if (arg_count !=2 ) {
        cerr << "expected one argument" << endl;
        return EXIT_FAILURE;      
    }

    string line;
    ifstream myfile (arg_vec[1]);

    FILE *f=fopen(myfile,"rb");
    int c=0,b;
    while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
    fseek(f,0,SEEK_SET);


    return 0;
}
+3
source share
5 answers
FILE *f=fopen(filename,"rb");

int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);

Answer in c. Such a compact?

+6
source

, " ", , , .

, , std::vector<string> - . , :

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::fstream file("main.cpp");
    std::vector<std::string> fileData;

    // read in each line
    std::string dummy;
    while (getline(file, dummy))
    {
        fileData.push_back(dummy);
    }

    // and size is available, along with the file
    // being in memory (faster than hard drive)
    size_t fileLines = fileData.size();

    std::cout << "Number of lines: " << fileLines << std::endl;
}

:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::fstream file("main.cpp");
    size_t fileLines = 0;    

    // read in each line
    std::string dummy;
    while (getline(file, dummy))
    {
        ++fileLines;
    }

    std::cout << "Number of lines: " << fileLines << std::endl;
}

, . , .

+10

, ...

std::ifstream file(f);
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n') + 1;
+10
#include <stdlib.h>
int main(void) { system("wc -l plainfile.txt"); }
+3

Count the number of copies '\n'. This works for line endings * nix (\ n) and DOS / Windows (\ r \ n), but not for the old Mac (system 9 or maybe before) that only used \ r. I have never seen a case come up with only \ r as line endings, so I would not worry about it if you did not know that this would be a problem.

Edit: if your input is not ASCII, you may also encounter encoding problems. What does your entrance look like?

+1
source

Source: https://habr.com/ru/post/1714276/


All Articles