Search code examples
clinuxfopensamba

Linux fopen() syntax for samba share


I am trying to use the following syntax for fopen() to access a samba share.

FILE *of = fopen("smb://sambadevice/folder/filename.txt", "w");

but this is not working (errno = 2).

Does anyone know the correct syntax for a samba share?

PS - if I type "smb://sambadevice/folder" into Dolphin, it opens the folder.


Solution

  • fopen doesn't understand any syntax. There are no special filename forms you can pass it in order to access anything special, nothing other than an ordinary filename path in (what appears to be) the local filesystem.

    When you pass a pathname to fopen, typically it doesn't parse or inspect the pathname string in any way; it just passes it on to the underlying open system call. And then open doesn't do much more than a very basic parse of the pathname, either: all it does is split it on / characters so that it can walk the path (work down through any directories and subdirectories) to find the requested file. This is in keeping with an important tenet of the Unix philosophy, namely "everything's a file".

    This absolutely does not mean, however, that there's no way to access Samba-mounted fileshares using a C program that calls fopen. If you want to access Samba-mounted fileshares, you need to figure out how to mount them in the local filesystem. There are lots of ways to do this. Me, I use the command mount.cifs. People in the comments have also mentioned GVfs, KioFuse, and Smb4K.

    Once you've got your Samba file share mounted (or, similarly, once you've got any resource mounted) as if it were a file or directory in the local filesystem, you can access via its pathname just as if -- well, just as if it were a file or directory in the local filesystem. (And of course you can access it via any tool or application, whether or not it's a C program calling fopen.)

    So on a Unix or Linux system you typically won't see any explicit smb:// syntax in the pathname you open. Typically the pathname you open will start with /mnt or /cifs or /home/myname/.gvfs -- that is, wherever in the filesystem the Samba share has been mounted.