Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get device name on which a file is located from its path in c?

Tags:

c

linux

device

Let's say I have a file in Linux with this path:

/path/to/file/test.mp3

I want to know the path to its device. For example I want to get something like:

/dev/sdb1

How do I do this with the C programming language?

I know the terminal command to do it, but I need C functions that will do the job.

EDIT: I have read this question before asking mine. It doesn't concretly mention code in C, it's more related to bash than to the C language.

Thanks.

like image 699
Mehdi Ijadnazar Avatar asked Jul 27 '16 14:07

Mehdi Ijadnazar


1 Answers

You need to use stat on the file path, and get the device ID st_dev and match that to a device in /proc/partitions

Read this for how to interpret st_dev: https://web.archive.org/web/20171013194110/http://www.makelinux.net:80/ldd3/chp-3-sect-2

like image 96
Salgar Avatar answered Nov 13 '22 16:11

Salgar