🔊 Nesse vídeo vamos ver como fazer parser de CSV com C++ sem nenhuma biblioteca pronta para isso e aproveitar para utilizar algumas ferramentas modernas e recursos, tais como:
file.csv
Bjarne Stroustroup,1979,C++,bjarne@stroustroup.com
Dennis Ritchie,1970,C,dennis@ritchie.net
Maurice Wilkes,1940,Assembly,maurice@wilkes.us
Brian Kernighan,1977,AWK,brian@kernighan.org
Anonymous,,,anom@null.net
main.cpp
#include <fmt/format.h>
#include <fstream>
#include <cstring>
#include <array>
auto main(int argc, char **argv) -> int {
if(argc > 1){
std::string line {};
std::ifstream file(argv[1]);
if(file.is_open()){
const char * delim = ",";
std::array<std::string, 4> fields {"NAME", "YEAR", "LANG", "MAIL"};
int i {};
while(std::getline(file, line)){
char * buf = &line[0];
char * pline = strsep(&buf, delim);
while(pline != NULL){
fmt::print("{}: {}\n", fields[i], pline);
pline = strsep(&buf, delim);
++i;
if(i > 3){
fmt::print("-------\n");
i = 0;
}
}
}
file.close();
}
}else{
fmt::print(stderr, "Use: {} file.csv\n", argv[0]);
}
}
Makefile
TARGET=a.out
CC=g++ -std=c++23
DEBUG=-g
OPT=-O1
WARN=-Wall -Werror -Wextra -Wpedantic
FMT=-lfmt
CCFLAGS=$(DEBUG) $(OPT) $(WARN)
LD=g++
OBJS= main.o
all: $(OBJS)
$(LD) -o $(TARGET) $(OBJS) $(FMT)
@rm -f *.o
main.o: main.cpp
$(CC) -c $(CCFLAGS) main.cpp -o main.o $(FMT)
CMakeLists.txt
cmake_minimum_required(VERSION 3.26.3)
project(cppsv
LANGUAGES CXX
VERSION 0.0.1
)
add_compile_options(-Wall -Werror -Wextra -Wpedantic)
set (CMAKE_CXX_STANDARD 23)
add_executable(a.out main.cpp)
find_package(fmt)
target_link_libraries(a.out PRIVATE fmt::fmt-header-only)