https://www.tutorialspoint.com/unix/unix-io-redirections.htm

 

Unix / Linux - Shell Input/Output Redirections

Unix Linux Shell Input Output Redirections - In this chapter, we will discuss in detail about the Shell input/output redirections. Most Unix system commands take input from your terminal and send the resulting output back to your terminal. A command normal

www.tutorialspoint.com

Output Redirection

$ who > users
$ cat users
user	tty01	Sep 12 07:30
:

Example

$ echo line 1 > lines
$ cat lines
line 1
$

$ echo line 2 >> lines
$ cat lines
line 1
line 2
$

 

Input Redirection

The commands that normally take their input from the standard input can have their input redirected from a file in this manner.

For example, to count the number of lines in the file lines generated above,
you can execute the command as follows -

$ wc -l lines
2 lines
$

$ wc -l < lines
2
$

$ wc -l << EOF
> This is a simple lookup program
> for good (and bad) restaurants
> in Cape Town.
> EOF
3
$

 

Here Document

A here document is used to redirect input into an interactive shell script or program.

We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script.

The general form for a here document is -

command << delimiter
document
delimiter

 

Here the shell interprets the << operator as an instruction to read input until it finds a line containing the specified delimiter. All the input lines up to the line containing the delimiter are then fed into the standard input of the command.

 

The delimiter tells the shell that the here document has completed.

Without it, the shell continues to read the input forever.

The delimiter must be a single word that does not contain spaces or tabs.

 

Follwing is the input to the command wc -l to count the total number of lines -

$ wc -l << EOF
> This is a simple lookup program
> for good (and bad) restaurants
> in Cape Town.
> EOF
3
$

You can use the here document to print multiple lines using your script as follows -

#!/bin/sh

cat << EOF
This is a simple lookup program 
for good (and bad) restaurants
in Cape Town.
EOF

Result

This is a simple lookup program
for good (and bad) restaurants
in Cape Town.

 

Discard the output

Sometimes you will need to execute a command, but you don't want the output displayed on the screen.

In such cases, you can discard the output by redirecting it to the file /dev/null -

$ command > /dev/null

The file /dev/null is a special file that automatically discards all its input.

 

To discard both output of a command and its error output,
use standard redirection to redirect STDERR to STDOUT -

$ command > /dev/null 2>&1

Here 2 represents STDERR and 1 represents STDOUT.

 

You can display a message on to STDERR by redirecting STDOUT into STDERR as follows

$ echo message 1>&2

 

Redirection Commands

Sequence Command Description
1 pgm > file Output of pgm is redirected to file
2 pgm >> file Output of pgm is appeded to file
3 pgm < file Program pgm read its input from file
4 n > file Output from stream with descriptor n redirected to file
5 n >> file Output from stream with descriptor n appended to file
6 n >& m Merges output from stream n with stream m
7 n <& m Merges input from stream n with stream m
8 << tag Standard input comes from here through next tag at the start of file
9 | Takes output from one program, or process, and sends it to another

the file descriptor

  • 0 = normally standard input (STDIN)
  • 1 = standard output (STDOUT)
  • 2 = standard error output (STDERR)

'OS > Linux' 카테고리의 다른 글

Linux Shell Script  (0) 2023.08.09
LD_LIBRARY_PATH  (0) 2022.12.21
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

에https://www.tutorialspoint.com/unix/shell_scripting.htm

 

Shell Scripting Tutorial

Shell Scripting Tutorial - A shell script is a computer program designed to be run by the Unix/Linux shell which could be one of the following:

www.tutorialspoint.com

 

기본 구조

파일명: test.sh

#!/bin/sh

echo "Hello, World"
  • 확장자: .sh
  • 첫 번째 행에 해당 쉘 명시
    • #!bin/sh
    • #!bin/bash
  • 쉘 스크립트 파일을 실행시키려면 실행 권한을 줘야 함
$ chmod 755 test.sh

실행

$ ./test.sh
or
$ sh test.sh
or
$ bash test.sh

 

기본 문법

주석(comment)

#으로 시작

 

입력/출력

  • 입력: read
  • 출력: echo
#!/bin/sh

read NAME
echo "Hello, $NAME!"

결과

$ ./test.sh
dozob
Hello, dozob!

 

※ Tip

Bash에서는 -e 플래그로 특수 문자를 escape 할 수 있음

#!bin/bash

echon -e "Hello\n$NAME!"	# 개행('\n')됨

 

Variables

  • 변수 이름으로 영문자, 숫자, 언더바('_') 사용
  • 변수에 값을 할당할 때 '='의 앞뒤에 공백이 없어야 함
  • 문자열인 경우 쌍따옴표(")로 감싸야 함
  • 변수를 사용할 때는 앞에 $를 붙임, 변수는 {}로 감쌀 수 있음
  • readonly 키워드를 앞에 붙여 읽기 전용 변수를 정의할 수 있음
  • 변수 삭제는 unset으로 가능하나 readonly 변수는 삭제 못함
#!/bin/sh

var1=1234
var2="text"

echo "var2=$var2"

readonly var3="initialized readonly variable"
var3="try to assign readonly variable"

unset var2

결과

$ ./test.sh
var2=text
./test.sh: 9: var3: is read only

 

Special Variables

변수 기능
$0 스크립트명
$1 ~ $9 N번째 인수
$# 스크립트에 전달된 인수 개수
$* 모든 인수를 모아 하나로 처리
$@ 모든 인수를 각각 처리
$? 직전에 실행한 명령(command)의 종료 값
(성공: 0, 실패: 1)
$$ 쉘 스크립트의 프로세스 ID
$! 마지막으로 실행한 백그라운드 프로세스 ID

 

Metacharacters (특수 문자)

* ? [ ] ' " \ $ ; & ( ) | ^ < > new-line space tab

문자열 내에 쓰일 때는 '\'를 앞에 붙여야 함

Sequence Quoting Description
1 Single quote All special characters between these quotes lose their special meaning.
2 Double quote Most special characters between these quotes lose their special meaning
with these exceptions -
 - $, `, \$, \', \", \\
3 Backslash Any character immediately following the backslash loses its special meaning.
4 Back quote Anything in between back quotes would be treated as a command and would be executed.

Example

#!/bin/bash

echo <-$1500.**>; (update?) [y|n]
# -bash: syntax error near unexpected token `;'
echo \<-\$1500.\*\*\>\; \(update\?\) \[y\|n\]
echo '<-$1500.**>; (update?) [y|n]'

echo 'It\'s Shell Programming
# It\s Shell Programming

echo 'It\'s Shell Programming'
# Syntax error: Unterminated quoted string

VAR=ZARA
echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]"
# ZARA owes <-$1500.**>; [ as of (07/02) ]

 

변수 값의 치환

문법 설명
${var} 변수 값으로 치환
${var:-word} if var is null or unset, word is substitued for var.
The value of var does not change.
${var:=word} if var is null or unset, var is set to the value of word.
${var:+word} if var is set, word is substituted for var.
The value of var does not change.
${var:?message} If var is null or unset, message is printed to standard error.
This checks that variables are set correctly.
#/bin/sh

echo "1. \${var:-default value1}: \"${var:-default value1}\", var=${var}"
echo "2. \${var:=default value2}: \"${var:=default value2}\", var=${var}"

var="assigned value"
echo "var=\"assigned value\""
echo "3. \${var:+default value3}: \"${var:+default value3}\", var=${var}"
echo "4. \${var:?default value4}: \"${var:?default value4}\", var=${var}"

unset var
echo "unset var"
echo "5. \${var:+default value5}: \"${var:+default value5}\", var=${var}"
echo "6. \${var:?default value6}:"
echo " \"${var:?default value6}\", var=${var}"

결과

$ ./test.sh
1. ${var:-default value1}: "default value1", var=
2. ${var:=default value2}: "default value2", var=default value2
var="assigned value"
3. ${var:+default value3}: "default value3", var=assigned value
4. ${var:?default value4}: "assigned value", var=assigned value
unset var
5. ${var:+default value5}: "", var=
6. ${var:?default value6}:
./test.sh: line 15: var: default value6

 

Arrays

#!/bin/bash

# bash shell
ARRAY=(item item2 item3 item4)
ARRAY[0]="ITEM1"
ARRAY[2]="ITEM3"

echo "ARRAY[0]: ${ARRAY[0]}"
echo "ARRAY[2]: ${ARRAY[2]}"

echo "ARRAY[*]: ${ARRAY[*]}"
echo "ARRAY[@]: ${ARRAY[@]}"

결과

$ ./test.sh
ARRAY[0]: ITEM1
ARRAY[2]: ITEM3
ARRAY[*]: ITEM1 item2 ITEM3 item4
ARRAY[@]: ITEM1 item2 ITEM3 item4

 

Arithmetic Operators

Operator Description Example: a=10, b=20
+ Addition echo `expr $a + $b` → 30
- Substraction echo `expr $a - $b` → -10
\* (Multiplication) Multiplies values on either side of the operator echo `expr $a \* $b` → 200
/ (Division) Divide left hand operand by right hand operand echo `expr $b / $a` → 2
% (Modulus) evide left hand operand by right hand operand and returns remainder expr `expr $b % $a` → 0
= (Assignment) Aissigns right operand in left operand a=$b
== (Equality) Compares two numbers,
if both are same then returns true.
[ $a == $b ] → false
!= (Not Equality) Compares two numbers,
if both are different then return true.
[ $a != $b ] → true

※ Tip

for example, [ $a == $b ] is correct

whereas, [$a==$b] is incorrect

 

 

Relational / Boolean / String Operators

Operator Description Example
-eq equal [ $a -eq $b ]
-ne not equal [ $a -ne $b ]
-gt greater than [ $a -gt $b ]
-lt less than [ $a -lt $b ]
-ge greater than or equal to [ $a -ge $b ]
-le less than or equal to [ $a -le $b ]
Boolean Operators
! logical negation [ ! false ] → true
-o logical OR [ $a -lt 20 -o $b -gt 100 ] → true
-a logical AND [ $a -lt 20 $b -gt 100 ] → false
String Operators
= equal [ $a = $b ] → not true.
!= not equal [ $a != $b ] → true
-z Checks if the given string operand size is zero;
if it is zero length, then is returns true.
[ -z $a ] → not ture
-n Checks if the given string operand size is non-zero;
if it is nonzero length, then it returns true.
[ -n $a ] → not false
str Checks if str is not the empty string;
if it is empty, then it returns false.
[ $a ] → not false.

 

File Test Operators

Assume a variable file holds an existing file name "test" the size of which is 100 bytes and has read, write and execute permission on -

Operator Description: Checks if file ~ Example
-e file file exists; is true even if file is a directory but exists. [ -e $file ] → true
-s file file has size greater then 0 [ -s $file ] → true
     
-b file block special file [ -b $file ] → false
-c file character special file [ -c $file ] → false
-d file directory [ -d $file ] → not true
-p file named pipe [ -p $file ] → false
-f file an ordinary file as opposed to a directory or special file [ -f $file ] → true
-t file file descriptor is open and associated with a terminal [ -t $file ] → false
     
-g file has its Set Group ID (SGID) bit set [ -g $file ] → false
-k file has its Sticky bit set [ -k $file ] → false
-u file has its Set User ID (SUID) bit set [ -u $file ] → false
     
-r file readable [ -r $file ] → true
-w file writable [ -w $file ] → true
-x file executable [ -x $file ] → true

 

Decision Making

if ... else

  • if ... fi
  • if ... else ... fi
  • if ... elif ... else ... fi

 

case ... esac

  • case ... esac

case VARIABLE in CONDITION/VALUE) Command ;; esac

#!/bin/sh

DRINK="coffee"
case "$DRINK" in
    "beer") echo "맥주"
    ;;
    "juice") echo "주스"
    ;;
    "coffee") echo "커피"
    ;;
esac

 

 

Loops

  • while
  • for
  • until
  • select
while command1 ;	# this is loop1, the outer loop
do
    Statement(s) to be executed if command1 is true
    
    while command2 ;	# this is loop2, the inner loop
    do
        Statement(s) to be executed if command2 is ture
    done
    
    Statements(s) to be executed if command1 is true
done

 

Example

#!/bin/sh

a=0
while [ "$a" -lt 10 ]	# this is loop1
#until [ "$a" -ge 10 ]
do
    b="$a"
    
    while [ "$b" -ge 0 ]	# this is loop2
    #until [ "$b" -lt 0 ]
    do
        echo -n "$b "		# -n option lets echo avoid printing a new line character
        b=`expr $b - 1`
    done
    
    echo
    
    a=`expr $a + 1`
done

Result

0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

 

Example

#!/bin/sh

for var1 in 1 2 3
do
   for var2 in 0 5
   do
      if [ $var1 -eq 2 -a $var2 -eq 0 ]
      then
         break 2
      else
         echo "$var1 $var2"
      fi
   done
done

Result

1 0
1 5

 

Example

#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "$NUM: Number is an even number!"
      continue
   fi
   echo "$NUM: Found odd number"
done

bash

#!/bin/bash

# using array
NUMS=(1 2 3 4 5 6 7)

for NUM in ${NUMS[*]}
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "$NUM: Number is an even number!"
      continue
   fi
   echo "$NUM: Found odd number"
done

 

Result

1: Found odd number
2: Number is an even number!!
3: Found odd number
4: Number is an even number!!
5: Found odd number
6: Number is an even number!!
7: Found odd number

 

Substitution

Sequence Escape Description
1 \\ backslash
2 \a alert (BEL)
3 \b backspace
4 \c suppress trailing newline
5 \f form feed
6 \n new line
7 \r carriage return
8 \t horizontal tab
9 \v vertical tab

You can use the -E option to disable the interpretation of the backslash escapes (default).

You can use the -e option to enable the interpretation of the backslash escapes.

You can use the -n option to disable the insertion of a new line.

 

Command Substitution

Command substitution is the mechanism by which the shell performs a given set of commands

and then substitues their output in the place of the commands.

Syntax

`command`

When performing the command substitution make sure that you use the backquote, not the single quote character.

 

Example

#!/bin/sh

DATE=`date`
echo "Date is $DATE"

USERS=`who | wc -l`
echo "Logged in user are $USERS"

UP=`date ; uptime`
echo "Uptime is $UP"

Result

Date is Wed Aug  9 16:54:06 KST 2023
Logged in user are 0
Uptime is Wed Aug  9 16:54:06 KST 2023
 16:54:06 up 10 days, 14:15,  0 users,  load average: 0.03, 0.01, 0.00

 

'OS > Linux' 카테고리의 다른 글

Linux Shell - IO Redirections  (0) 2023.08.09
LD_LIBRARY_PATH  (0) 2022.12.21
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

이 환경변수(environment variable)을 이용해 shared library 참조

 

$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/nvidia/deepstream/deepstream-6.1/lib

이 설정은 터미널이 닫히면 사라진다.

따라서, "~/.bashrc" 파일을 직접 수정해 줘야 함

 

.bashrc

별칭(alias)과 bash가 수행될 때 실행되는 함수를 제어하는 지역적인 시스템 설정과 관련된 파일

모든 프로그램이 실행되기 전에 수행됨

적당한 위치에 LD_LIBRARY_PATH 설정문을 넣어둔다.

 

$ nano ~/.bashrc
...
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/nvidia/deepstream/deepstream-6.1/lib
...

 

ldconfig

기본 설정 파일은 /etc/ld.so.conf

파일 내용은 아래와 같다.

include /etc/ld.so.conf.d/*.conf

추가하려는 경로는 ld.so.conf.d 디렉토리 안에 파일을 생성해서 넣으면 된다.

 

'OS > Linux' 카테고리의 다른 글

Linux Shell - IO Redirections  (0) 2023.08.09
Linux Shell Script  (0) 2023.08.09
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

CUDA Support for WSL 2

https://docs.nvidia.com/cuda/wsl-user-guide/index.html#cuda-support-for-wsl2

 

CUDA on WSL :: CUDA Toolkit Documentation

Whether to efficiently use hardware resources or to improve productivity, virtualization is a more widely used solution in both consumer and enterprise space. There are different types of virtualizations, and it is beyond the scope of this document to delv

docs.nvidia.com

The lastest NVIDIA Windows GPU Driver will fully support WSL 2.

With CUDA support in the driver, existing applications (compiled elsewhere on a Linux system for the same target GPU)

can run unmodified with the WSL environment.

 

To compile new CUDA applications, a CUDA Toolkit for Linux x86 is needed.

CUDA Toolkit support for WSL is still in preview stage as developer tools such as profilers are not available yet.

However, CUDA application development is fully supported in the WSL 2 environment, as a result, users should be able to compile new CUDA Linux applications with the lastest CUDA Toolkit for x86 Linux.

 

Once a Windows NVIDIA GPU driver is installed on the system, CUDA becomes available within WSL 2.

The CUDA driver installed on Windows host will be stubbed inside the WSL 2 as libcuda.so,

therefore users must not install any NVIDIA GPU Linux driver within WSL 2.

One has to be very careful here as the default CUDA Toolkit comes packaged with a driver,

and it is easy to overwrite the WSL 2 NVIDIA driver with the default installation.

We recommend developers to use a separate CUDA Toolkit for WSL 2 (Ubuntu) available here to avoid this overwriting.

 

https://docs.nvidia.com/cuda/archive/11.7.1/cuda-installation-guide-linux/index.html#wsl-installation

 

Installation Guide Linux :: CUDA Toolkit Documentation

Check that the device files/dev/nvidia* exist and have the correct (0666) file permissions. These files are used by the CUDA Driver to communicate with the kernel-mode portion of the NVIDIA Driver. Applications that use the NVIDIA driver, such as a CUDA ap

docs.nvidia.com

 

0. Remove CUDA files

$ sudo apt-get remove --purge '^nvidia-.*'
 
$ sudo apt-get remove --purge 'cuda*'
$ sudo apt-get autoremove --purge 'cuda*'
 
$ sudo rm -rf /usr/local/cuda
$ sudo rm -rf /usr/local/cuda-#.#

 

1. Prepare WSL

1.1. Remove Outdated Signing key:

$ sudo apt-key del 7fa2af80

 

2. Local Repo Installation for WSL

2.1. Install local repository on file system:

$ wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-wsl-ubuntu.pin
$ sudo mv cuda-wsl-ubuntu.pin /etc/apt/preferences.d/cuda-repository-pin-600

$ wget https://developer.download.nvidia.com/compute/cuda/11.7.1/local_installers/cuda-repo-wsl-ubuntu-11-7-local_11.7.1-1_amd64.deb
$ sudo dpkg -i cuda-repo-wsl-ubuntu-11-7-local_11.7.1-1_amd64.deb

2.2. Enroll ephemeral public GPG key:

$ sudo cp /var/cuda-repo-wsl-ubuntu-11-7-local/cuda-96193861-keyring.gpg /usr/share/keyrings/

 

3. Network Repo Installation for WSL

The new GPG public key for the CUDA repository (Debian-base distros) is 3bf863cc.

(https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/3bf863cc.pub)

This must be enrolled on the system, either using the cuda-keyring package or manually;

the apt-key command is deprecated and not recommended.

3.1. Install the newcuda-keyring package:

$ wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-keyring_1.0-1_all.deb
$ sudo dpkg -i cuda-keyring_1.0-1_all.deb

 

4. Common Installation Instructions for WSL

These instructions apply to both local and network installation for WSL.

4.1. Update the Apt repository cache:

$ sudo apt-get update

4.2. Install CUDA SDK:

$ sudo apt-get -y install cuda

$ sudo apt-get -y install cuda-toolkit-11-7

The installation instructions for the CUDA Toolkit can be found in the CUDA Toolkit download page for each installer.

But DO NOT choose the "cuda", "cuda-11-8", "cuda-drivers" meta-packages under WSL 2

as these packages will result in an attempt to install the Linux NVIDIA driver under WSL 2.

Install the cuda-toolkit-11-x metapackage only.

 

4.3. Perform the post-installation actions.

The post-installation actions must be manually performed.

These actions are split into mandatory, recommended, and optional sections.

 

5. Post-installation Actions

5.1. Mandatory Actions

Some actions must be taken after the installation before the CUDA Toolkit and Driver can be used.

5.1.1. Environment Setup

The PATH variable needs to include export PATH=/usr/local/cuda-11.7/bin${PATH:+:${PATH}}.

Nsight Compute has moved to /opt/nvidia/nsight-compute/ only in rpm/deb installation method.

When using .run installer it is still located under /usr/local/cuda-11.7/.

 

To add this path to the PATH variable:

$ export PATH=/usr/local/cuda-11.7/bin${PATH:+:${PATH}}

In addition, when using the runfile installation method,

the LD_LIBRARY_PATH variable needs to contain

  • /usr/local/cuda-11.7/lib64 on a 64-bit system, or
  • /usr/local/cuda-11.7/lib on a 32-bit system

To change the environment variables for 64-bit operating systems:

export LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

5.1.2 POWER9 Setup

Because of the addition of new features specific to the NVIDIA POWER9 CUDA driver,

there are some additional setup requirements in order for the driver to function properly.

These additional steps are not handled by the installation of CUDA packages,

and failure to ensure these extra requirements are met will result in a non-functional CUDA driver installation.

 

There are two changes that need to be made manually after installing the NVIDIA CUDA driver to ensure proper operation:

1. The NVIDIA Persistence Daemon should be automatically started for POWER9 installations.

    Check that it is running with the following command:

$ sudo systemctl status nvidia-persistenced

 

2. Disable a udev rule installed by default in some Linux distributions

that cause hot-pluggable memory to be automatically onlined when it is physically probed.

This behavior prevents NVIDIA software from bringing NVIDIA device memory online with non-default settings.

This udev rule must be disabled in order for the NVIDIA CUDA driver to function properly on POWER9 systems.

 

 

 

 

 

'OS > Linux' 카테고리의 다른 글

Linux Shell Script  (0) 2023.08.09
LD_LIBRARY_PATH  (0) 2022.12.21
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06
CUDA-11.4 on WSL2  (0) 2022.10.12

Reference:

https://www.it-note.kr/173

 

stat(2) - 파일의 상태 및 정보를 얻는 함수

stat(2) #include #include #include int stat(const char *path, struct stat *buf); 파일의 크기, 파일의 권한, 파일의 생성일시, 파일의 최종 변경일 등, 파일의 상태나 파일의 정보를 얻는 함수입니다. stat(2) 함수는 s

www.it-note.kr

 

#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>


#if 0
struct stat {
    __dev_t     st_dev;     /* Device. */
    __ino_t     st_ino;     /* File serial number */
    __nlink_t   st_nlink;   /* Link count. */
    __mode_t    st_mode;    /* File mode. */
    __uid_t     st_uid;     /* User ID of the file's owner. */
    __gid_t     st_gid;     /* Group ID of the file's group. */
    __dev_t     st_rdev;    /* Device number, if device. */
    __off_t     st_size;    /* Size of file, in bytes. */
    __blksize_t st_blksize; /* Optimal block size for I/O */
    __blkcnt_t  st_blocks;  /* Number 512-byte blocks allocated. */
    /**
     * Nanosecond resolution timestamps are stored in a format
     * equivalent to 'struct timespec'.
     * This is the type used whenever possible
     * but the Unix namespace rules do not allow the identifier 'timespec'
     * to appear in the <sys/stat.h> header.
     * Therefore we have to handle the use of this header
     * in strictly standard-compliant sources sepcial.
     */
    time_t      st_atime;   /* time of last access */
    time_t      st_mtile;   /* time of last modification */
    time_t      st_ctime;   /* time of last status change */
};

int stat(const char *path, struct stat *buf);
#endif


inline bool fs_file_exists(const char *path)
{
    struct stat buffer;
    return stat(path, &buffer) == 0;
}

int example(const char *path)
{
    struct stat sb;
    
    if (stat(path, &sb) == -1)
    {
        // 오류, 상세한 오류 내용은 errno 전역변수에 설정
        perror("stat");
        return errno;
    }
    
    switch (sb.st_mode & S_IFMT)
    {
    case S_IFBLK:  printf("block device\n");     break;
    case S_IFCHR:  printf("character device\n"); break;
    case S_IFDIR:  printf("directory\n");        break;
    case S_IFIFO:  printf("FIFO/pipe\n");        break;
    case S_IFLNK:  printf("symlink\n");          break;
    case S_IFREG:  printf("regular file\n");     break;
    case S_IFSOCK: printf("socket\n");           break;
    default:       printf("unknown?\n");         break;
    }
    
    printf("I-node number:            %ld\n", (long) sb.st_ino);
    printf("Mode:                     %lo (octal)\n", (unsigned long) sb.st_mode);
    printf("Link count:               %ld\n", (long) sb.st_nlink);
    printf("Ownership:                UID=%ld   GID=%ld\n", (long) sb.st_uid, (long) sb.st_gid);
    printf("Preferred I/O block size: %ld bytes\n",         (long) sb.st_blksize);
    printf("File size:                %lld bytes\n",        (long long) sb.st_size);
    printf("Blocks allocated:         %lld\n",              (long long) sb.st_blocks);
    printf("Last status change:       %s", ctime(&sb.st_ctime));
    printf("Last file access:         %s", ctime(&sb.st_atime));
    printf("Last file modification:   %s", ctime(&sb.st_mtime));
    
    return 0;
}

 

#include <iostream>
#include <string>
#include <sys/stat.h>   // stat
#include <errno.h>      // errno, ENOENT, EEXIST
#if defined(_WIN32)
#   include <direct.h>  // _mkdir
#endif


bool fs_file_exists(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    return !_stat(path.c_str(), &info);
#else
    struct stat info;
    return !stat(path.c_str(), &info);
#endif
}

bool fs_dir_exists(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    return _stat(path.c_str(), &info)
        ? false
        : (info.st_mode & _S_IFDIR) != 0;
#else
    struct stat info;
    return stat(path.c_str(), &info)
        ? false
        : (info.st_mode & S_IFDIR) != 0;
#endif
}

bool fs_mkdir(const std::string& path)
{
#if defined(_WIN32)
    int rv = _mkdir(path.c_str());
#else
    mode_t mode = 0755;
    int rv = mkdir(path.c_str(), mode);
#endif

    if (rv)
    {
        switch (errno)
        {
        case ENOENT:
            // parent didn't exist, try to create it
            {
                int pos = path.find_last_of('/');
                if (pos == std::string::npos)
#if defined(_WIN32)
                    pos = path.find_last_of('\\');
                if (pos == std::string::npos)
#endif
                    return false;
                
                if (!fs_mkdir(path.substr(0, pos)))
                    return false;
            }
            // now, try to create again
#if defined(_WIN32)
            return !_mkdir(path.c_str());
#else
            return !mkdir(path.c_str(), mode);
#endif
        case EEXIST:
            // done!
            return fs_dir_exists(path);

        default:
            return false;
        }
    }

    return true;
 }

'OS > Linux' 카테고리의 다른 글

LD_LIBRARY_PATH  (0) 2022.12.21
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Install libjpeg-turbo  (0) 2022.11.06
CUDA-11.4 on WSL2  (0) 2022.10.12
Ubuntu에서 GPG ERROR NO_PUBKEY 해결방법  (0) 2022.10.11

+ Recent posts