https://fmt.dev/latest/index.html

 

Overview — fmt 9.1.0 documentation

Overview {fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams. What users say: Thanks for creating this library. It’s been a hole in C++ for a long time. I’ve used both boost::format and loki::SP

fmt.dev

fmt 라는 문자열 format 라이브러리가 있다. 헤더만 추가하고 FMT_HEADER_ONLY 만 선언해줘도 사용 가능해서 사용하기 편하다.

https://en.cppreference.com/w/cpp/utility/format

 

Formatting library (since C++20) - cppreference.com

The text formatting library offers a safe and extensible alternative to the printf family of functions. It is intended to complement the existing C++ I/O streams library. [edit] Formatting functions stores formatted representation of the arguments in a new

en.cppreference.com

#include <cassert>
#include <format>
 
int main()
{
    std::string message = std::format("The answer is {}.", 42);
    assert( message == "The answer is 42." );
}

c++ 20 부터 추가된 formatting 라이브러리를 사용하면 되는데 printf format specifier 인 % 구문이 아니라 {} 를 사용한다. 형식을 지정하지 않아도 되서 형식 지정 오류를 줄일 수 있다.

void f_withoutFmt()
{
	std::vector<int> items { 0, 1, 2, 3 };
	
	bool bFirst = true;
	
	std::string str;
	for (const auto& item : items)
	{
		if (! bFirst)
		{
			str.append(",");
		}
		str.append(std::to_string(item));
		bFirst = false;
	}
	
	std::cout << "items1 : " << str << std::endl;
}

vector 형식의 아이템들을 출력할 때 루프를 돌면서 문자열을 추가해주는 식으로 코드를 짜게 된다. 쓸데없이 길다.

void f_withFmt()
{
	std::vector<int> items { 0, 1, 2, 3 };
	
	std::cout << "items2 : " << fmt::format("{}", fmt::join(items, ",")) << std::endl;
}

fmt::join 을 이용할 경우 간결해진다.

https://stackoverflow.com/questions/59280481/convert-a-vectorint-to-string-with-fmt-library

 

Convert a vector<int> to string with fmt library

How to remove {} from the output? #include <iostream> #include <vector> #include <fmt/format.h> #include <fmt/ranges.h> int main () { std::vector<int> v = {1,2,3}...

stackoverflow.com

 

728x90
$ ls
a.txt  b.txt  c.txt  d.log  e.log

폴더에 여러 파일들이 있을 때 특정 파일들만 bash 로 처리할 일이 있었다. 예를 들어 위와 같은 폴더에서 txt 파일들만 처리하고 싶은 경우다.

#!/bin/bash

for f in *.txt
do
	echo $f
done

bash 에서는 for in 구문을 사용하면 됐다. in 영역에 *.txt 와 같이 표기해주면 된다.

$ ./for.sh
a.txt
b.txt
c.txt

실행하면 txt 확장자를 가진 파일명들이 출력된다.

https://www.cyberciti.biz/faq/bash-loop-over-file/

 

728x90

linux 로 서비스하니 tar.gz 로 압축해서 로그를 전달 받게 된다. 오랜만에 tar 를 써보니 파라미터가 생각나지 않아 메모해둔다.

$ tar --help
Usage: tar [OPTION...] [FILE]...
GNU 'tar' saves many files together into a single tape or disk archive, and can
restore individual files from the archive.

Examples:
  tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.
  tar -tvf archive.tar         # List all files in archive.tar verbosely.
  tar -xf archive.tar          # Extract all files from archive.tar.
$ ls
test2.txt

$ tar -cvf test2.tar test2.txt
test2.txt

$ ls
test2.tar  test2.txt

생성할 때는 c 옵션을 사용하게 된다.

  -c, --create               create a new archive
  -v, --verbose              verbosely list files processed
  -f, --file=ARCHIVE         use archive file or device ARCHIVE

c : 생성
v : 진행중인 파일 표시
f : 파일로 저장

$ tar -czvf test2.tar.gz test2.txt
test2.txt

$ ls
test2.tar  test2.tar.gz  test2.txt

압축을 하고 싶다면 z 옵션을 사용하면 된다.

  -z, --gzip, --gunzip, --ungzip   filter the archive through gzip

z : gzip 을 이용해 압축

$ tar -xvf test2.tar
test2.txt

묶인 파일 해제는 x 명령어를 사용한다.

$ tar -xzvf test2.tar.gz
test2.txt

gzip 으로 압축된 파일을 z 옵션을 추가해줘야 한다.

 Main operation mode:

  -A, --catenate, --concatenate   append tar files to an archive
  -c, --create               create a new archive
      --delete               delete from the archive (not on mag tapes!)
  -d, --diff, --compare      find differences between archive and file system
  -r, --append               append files to the end of an archive
  -t, --list                 list the contents of an archive
      --test-label           test the archive volume label and exit
  -u, --update               only append files newer than copy in archive
  -x, --extract, --get       extract files from an archive

다른 옵션 들도 많으니 tar --help 를 참고하자.

참고 : https://eehoeskrap.tistory.com/555

 

[Linux] tar / tar.gz / zip 압축 및 압축 해제

보통 리눅스에서 파일을 압축 파일을 다룰 때, "tar로 압축(compress)한다"는 표현을 쓰는 경우가 많은데, 정확히 말하자면 tar 자체는 "데이터의 크기를 줄이기 위한 파일 압축"을 수행하지 않는다.

eehoeskrap.tistory.com

 

728x90

윈도우즈 기본 설치하면 복구 파티션이 잡혀서 용량을 전부다 사용하지 못한다. 

디스크 관리 프로그램에서 다른 파티션과 달리 오른쪽 메뉴도 없어서 볼륨 삭제와 같은 작업을 진행할 수 없다.

관리자 권한으로 명령 프롬프트를 실행해서 diskpart 명령어를 통해 해당 파티션을 삭제할 수 있다.

C:\Windows\System32>diskpart

Microsoft DiskPart 버전 10.0.22621.1

Copyright (C) Microsoft Corporation.
컴퓨터: 

DISKPART> list disk

  디스크 ###  상태           크기     사용 가능     Dyn  Gpt
  ----------  -------------  -------  ------------  ---  ---
  디스크 0    온라인        465 GB       1024 KB
  디스크 1    온라인        476 GB           0 B
  디스크 2    온라인        931 GB       1024 KB
  디스크 3    온라인       1863 GB           0 B   *    *
  디스크 4    온라인        476 GB       2048 KB        *

DISKPART> select disk 4

4 디스크가 선택한 디스크입니다.

작업할 파티션이 위치한 디스크를 select disk 를 통해 선택하자.

DISKPART> list partition

  파티션 ###  종류              크기     오프셋
  ----------  ----------------  -------  -------
  파티션 1    복구                 450 MB  1024 KB
  파티션 2    시스템                 99 MB   451 MB
  파티션 3    예약됨                 16 MB   550 MB
  파티션 4    주                  475 GB   566 MB
  파티션 5    복구                 817 MB   476 GB

DISKPART> select partition 5

5 파티션이 선택한 파티션입니다.

작업할 파티션을 select partition 으로 선택하자.

DISKPART> delete partition override

DiskPart에서 선택한 파티션을 삭제했습니다.

DISKPART> EXIT

DiskPart 마치는 중...

해당 파티션을 삭제하자.

디스크 관리에서 해당 공간이 할당되지 않은 상태로 변경된 것을 확인할 수 있다.

볼륨 확장을 통해 다른 파티션에서 해당 공간을 사용하도록 확장할 수 있다.

참고 : https://itfix.tistory.com/969

 

복구 파티션 제거 후 파티션 확장하는 방법 - 쉬움

바탕화면의 내 PC를 우클릭한 다음 관리를 누르면 컴퓨터 관리라는 창이 뜨는 데 왼쪽의 디스크 관리를 선택하면 오른쪽 창에서 하드 디스크들의 파티션 상태를 확인할 수 있습니다. 제 경우에

itfix.tistory.com

 

728x90

가끔 Visual Studio 업데이트하다보면 80KB/초 와 같이 모뎀 시절 속도가 나오는 경우가 있다. 다른 경로로 업데이트 시도하기 위해 윈도우즈 hosts 파일을 수정해보자.

c:\Windows\System32\drivers\etc\hosts 파일을 관리자 권한으로 실행한 메모장같은 프로그램으로 열자.

#93.184.215.201 download.visualstudio.microsoft.com
#192.229.232.200 download.visualstudio.microsoft.com
#68.232.34.200 download.visualstudio.microsoft.com
#117.27.243.98 download.visualstudio.microsoft.com
#36.25.247.107 download.visualstudio.microsoft.com
#192.16.48.200 download.visualstudio.microsoft.com

위 문자열을 붙여넣고 저장한다. 사용할 ip 에 해당되는 줄의 #을 지우고 저장하면 download.visualstudio.microsoft.com 이 변경된다. 하나씩 바꿔가면서 나쁘지 않은 속도가 나오는 ip 를 사용하면 된다.

참고 : https://davi06000.tistory.com/11

 

[ VS 삽질 ] VisualStudio 설치 속도가 너무 느릴때

//서론 새로 설치해야하는 SDK와 기존에 설치되어있던 VS의 키트가 충돌을 일으켜서 VS를 지웠다가 깔아야하는 상황이었다. 그런데 설치 속도가 24KB/sec? 진짜 화가 머리끝까지 치미는 상황이다. //

davi06000.tistory.com

 

728x90
~$ ln /mnt/x/test test
ln: /mnt/x/test: hard link not allowed for directory
~$ ln -s /mnt/x/test test
~$ ls
test
~$ cd test
~/test$ pwd
/home/userX/test

linux 에서 디렉토리를 연결시킬 때 ln 명령어를 사용한다.

~$ ln --help
Usage: ln [OPTION]... [-T] TARGET LINK_NAME
  or:  ln [OPTION]... TARGET
  or:  ln [OPTION]... TARGET... DIRECTORY
  or:  ln [OPTION]... -t DIRECTORY TARGET...
In the 1st form, create a link to TARGET with the name LINK_NAME.
In the 2nd form, create a link to TARGET in the current directory.
In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.
Create hard links by default, symbolic links with --symbolic.
By default, each destination (name of new link) should not already exist.
When creating hard links, each TARGET must exist.  Symbolic links
can hold arbitrary text; if later resolved, a relative link is
interpreted in relation to its parent directory.

Mandatory arguments to long options are mandatory for short options too.
      --backup[=CONTROL]      make a backup of each existing destination file
  -b                          like --backup but does not accept an argument
  -d, -F, --directory         allow the superuser to attempt to hard link
                                directories (note: will probably fail due to
                                system restrictions, even for the superuser)
  -f, --force                 remove existing destination files
  -i, --interactive           prompt whether to remove destinations
  -L, --logical               dereference TARGETs that are symbolic links
  -n, --no-dereference        treat LINK_NAME as a normal file if
                                it is a symbolic link to a directory
  -P, --physical              make hard links directly to symbolic links
  -r, --relative              create symbolic links relative to link location
  -s, --symbolic              make symbolic links instead of hard links
  -S, --suffix=SUFFIX         override the usual backup suffix
  -t, --target-directory=DIRECTORY  specify the DIRECTORY in which to create
                                the links
  -T, --no-target-directory   treat LINK_NAME as a normal file always
  -v, --verbose               print name of each linked file
      --help     display this help and exit
      --version  output version information and exit

The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.
The version control method may be selected via the --backup option or through
the VERSION_CONTROL environment variable.  Here are the values:

  none, off       never make backups (even if --backup is given)
  numbered, t     make numbered backups
  existing, nil   numbered if numbered backups exist, simple otherwise
  simple, never   always make simple backups

Using -s ignores -L and -P.  Otherwise, the last option specified controls
behavior when a TARGET is a symbolic link, defaulting to -P.

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report ln translation bugs to <https://translationproject.org/team/>
Full documentation at: <https://www.gnu.org/software/coreutils/ln>
or available locally via: info '(coreutils) ln invocation'​

ln -s <TARGET> <LINK_NAME> 형태로 사용한다.

참고로 rm 으로 삭제한다.

참고 : https://fruitdev.tistory.com/85

 

리눅스 심볼릭 링크 생성 및 삭제

리눅스 심볼릭 링크는 특정 파일이나 디렉토리에 대하여 참조를 하는 특수한 파일이다. 쉽게 생각하면 윈도우에서 우리가 즐겨 사용하는 "바로가기"와 동일하다고 할 수 있다. 우리는 다양한 이

fruitdev.tistory.com

 

728x90
$ getconf -a | grep libc
GNU_LIBC_VERSION                   glibc 2.31

$ ldd --version
ldd (Ubuntu GLIBC 2.31-0ubuntu9.7) 2.31
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.

위 2가지 명령어를 통해 설치된 GLIBC 를 확인할 수 있다.

출처 : https://ososoi.tistory.com/79

 

[Linux/Unix] GLIBC 버전 확인하기

centos7에서 테스트 하였습니다. glibc 버전을 확인 하기 위해서 쉘에서 다음의 명령어 들로 확인 할 수 있다. $ getconf -a | grep libc GNU_LIBC_VERSION glibc 2.5 $ ldd --version ldd (GNU libc) 2.5 Copyright (C) 2006 Free Soft

ososoi.tistory.com

 

728x90
job="A" elapsed="12"
job="B" elapsed="234"
job="C" elapsed="3456"
job="D" elapsed="4"
job="E" elapsed="56"
job="F" elapsed="678"
job="G" elapsed="7890"

위와 같은 성능 로그가 있을 때 3자리 이상 걸린 로그를 찾고 싶을 때가 있다.

$ grep "elapsed=\"[0-9][0-9][0-9]\+\"" test.log
job="B" elapsed="234"
job="C" elapsed="3456"
job="F" elapsed="678"
job="G" elapsed="7890"

정규식 표현 중 하나 이상 있어야 한다는 + 표현을 사용해서 검색할 수 있다.

$ grep "elapsed=\"[0-9][0-9][0-9][0-9]*\"" test.log
job="B" elapsed="234"
job="C" elapsed="3456"
job="F" elapsed="678"
job="G" elapsed="7890"

0 회 이상을 뜻하는 * 표현을 사용할 수도 있다.

$ grep "elapsed=\"[0-9]\{2,3\}\"" test.log
job="A" elapsed="12"
job="B" elapsed="234"
job="E" elapsed="56"
job="F" elapsed="678"

n 회 이상 m 회 이하를 표현하는 {n,m} 표현을 통해 더 정밀하게 제어할 수도 있다.

$ grep "elapsed=\"[0-9]\{3,\}\"" test.log
job="B" elapsed="234"
job="C" elapsed="3456"
job="F" elapsed="678"
job="G" elapsed="7890"

m 부분을 비워 n 회 이상을 표현할 수도 있다.

728x90

VS 2022 를 사용중인데 define 된 코드에 마우스를 가져다대면 처리가 결과가 보이기도 한다.

전처리된 결과를 파일로 보고 싶으면 속성 페이지 > 구성 속성 > C/C++ > 전처리기 탭에서 '파일로 전처리' 항목을 '예(/P)' 로 선택하고 컴파일하면 된다. 중간 디렉터리에 i 확장자의 파일이 생성된다.

// 전처리 전
	return EXIT_SUCCESS;
}

SetWin32ConsoleApp(PpApp);

// 전처리 후

	return 0;
}

int wmain(int argc, wchar_t *argv[], wchar_t *envp[]) { return WmainT<PpApp>(argc, argv, envp); };

include 구문도 처리되어 파일 용량이 꽤 큰데 아래쪽에서 대상 cpp 파일의 처리 결과를 확인할 수 있다.

https://www.bestdev.net/397

 

Visual Studio.NET 2003에서 전처리 결과 소스 확인방법

Visual C++ 컴파일러 옵션 /P(파일 전처리)참고 항목 컴파일러 옵션 | 컴파일러 옵션 설정 /P 이 옵션을 사용하면 C 및 C++ 소스 파일을 전처리하여 전처리 결과를 파일에 씁니다. 파일의 기본 이름은

www.bestdev.net

 

728x90

앱 초기 실행 시에 동시에 스크립트를 로딩할 경우 파싱용 버퍼 때문에 동시에 메모리를 많이 사용하게 된다. 스크립트 파싱 후 메모리를 해제해도 os 로 바로 반환되지 않아 동시에 여러 앱을 실행하게 되면 os 메모리 부족이 발생할 수 있다. 초기화가 끝났다면 사용하지 않는 메모리를 바로 반환할 필요가 있다. 이 때 linux 에서는 malloc_trim 이라는 api 를 사용하면 된다.

https://man7.org/linux/man-pages/man3/malloc_trim.3.html

 

malloc_trim(3) - Linux manual page

malloc_trim(3) — Linux manual page MALLOC_TRIM(3) Linux Programmer's Manual MALLOC_TRIM(3) NAME         top malloc_trim - release free memory from the heap SYNOPSIS         top #include int malloc_trim(size_t pad); DESCRIPTION         top The

man7.org

Win32 에서는 HeapCompact 라는 api 를 사용했던 것 같다.

https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapcompact

 

HeapCompact function (heapapi.h) - Win32 apps

Returns the size of the largest committed free block in the specified heap. If the Disable heap coalesce on free global flag is set, this function also coalesces adjacent free blocks of memory in the heap.

learn.microsoft.com

 

728x90

+ Recent posts