Hi all,
I have a question about file path in lunix.
Since i pretty new to linux (im running ubuntu) i dont know how to give a correct file path to fopen command.
I want to write some data to a usb drive. Let me show you how i would do it in windows:

FILE *file;
file = fopen("j:\\test.txt", "w"); 	
fprintf(file,"some Data");	
fclose(file);

Where j: is my usb drive.
How can i do the same in ubuntu?

I know how i can write to my home dir:

const char filepath[] =
        "/home/alexander/file.txt";
file = fopen(filepath,"a+");

But i cant figure it out how i can write to a usb drive or another hdd.
can anyone help me out here?

thanks,
Alex

When mounting the drive, it's either implicitly or explicitly given a mount point. You use that mount point as the path (it's just a directory). For example using sda1 as the default mount point:

file = fopen("/dev/sda1/file.txt", "a+");

Though it would be a good idea to support a generic mount point in your C code, because the mount point could change with USB devices:

# mkdir /mnt/usbj
# mount /dev/sda1 /mnt/usbj
file = fopen("/mnt/usbj/file.txt", "a+");

It get a segmentation error when trying to open file.
see my code:

void PrintPacketInHex(unsigned char *packet, int len)
{
	unsigned char *p = packet;

	FILE *file;
	const char filepath[] =
		"/dev/sdb1/file.txt";
	file = fopen(filepath, "a+");

	cout << "---------Packet---Starts----" << endl;
	
	while(len--)
	{
		printf("%.2x ", *p); 
		fprintf(file,"%.2x ", *p);
		p++;
	}
	fprintf(file,"\n");
	cout << "\n--------Packet---Ends-----" << endl;
	
	fclose(file);
}

I sorta figured it out.
I looked in the disk utility and there was a mount point at: /media/ALEXANDER
ALEXANDER being my usb name.

void PrintPacketInHex(unsigned char *packet, int len)
{
	unsigned char *p = packet;

	FILE *file;
	const char filepath[] =
		"/media/ALEXANDER/file.txt";
	file = fopen(filepath, "a+");

	cout << "---------Packet---Starts----" << endl;
	
	while(len--)
	{
		printf("%.2x ", *p); 
		fprintf(file,"%.2x ", *p);
		p++;
	}
	fprintf(file,"\n");
	cout << "\n--------Packet---Ends-----" << endl;
	
	fclose(file);
}

i woult still like to figure it out how to do it with

"/dev/sdb1/file.txt"

in filepath.
Any ideas what might be wrong?

Though it would be a good idea to support a generic mount point in your C code, because the mount point could change with USB devices:

# mkdir /mnt/usbj
# mount /dev/sda1 /mnt/usbj
file = fopen("/mnt/usbj/file.txt", "a+");

Can you please explain the effect of this piece of code

hi,
it's a good tutorial,thanks a lot. But I create files in /mnt/usbdir and I see in /mnt/usbdir/.... something(using fopen and create files here) but I can't see anything in /media/sda1(this is myUsb) so how to see that ?

Regards
Erkan

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.