Heya,

Just trying to get a little help on some excercises I need to do, Done 14/15 fine, but stuck on 15th and not sure quite whats wrong.

Need to do a systemcall from C program to copy a file, using stat, open, read write and close.

So far I've done this:

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


int main(int argc, char *argv[]) {
struct stat TestFile;
int FileMode, FileMode2;
char line[2000];

printf("You have asked to read: %s\n", argv[1]);

if (stat(argv[2], &TestFile) == -1 && errno == ENOENT)
{
	printf("Secondary name doesn't exist, Proceeding.");
}
else
{
	printf("Error");
}

if (stat(argv[1], &TestFile) == -1 && errno == ENOENT)		// Checks if file exists, and if valid name
	{
	printf ("File %s doesn't exist.\n", argv[1]);
	}
else
	{
	if (stat(argv[1], &TestFile) == -1)
		{	
		printf ("Invalid name %s.\n", argv[1]);				// If invalid name report
		}
	else
		{
		printf ("File %s exists.\n", argv[1]);		// If it already exists report
		FileMode = open(argv[1], O_RDONLY);			// Opens read only file
		FileMode2 = open(argv[2], O_WRONLY|O_APPEND|O_CREAT, S_IRWXU);  //Creates file
		read(FileMode, line, 1024);							// Read file .
		fprintf(stdout, line);						// Outputs to stdout
		write(FileMode2, line, 1024);				// Writes to file
		close(FileMode2);							// Closes File
		close(FileMode);							// Closes File
		}
	}


return(0);
}

It copies a file and puts "something" into it, but I can't open the file as it complains about its character encoding :<

I wonder if it's due to my read/write statement being 1024 length, rather than looping a single bit around, but that doesn't seem to work either :<

Any help would be appreciated.

Thanks Steph

Nevermind I fixed it woot :P <3 Just used a struct of file info to find the file size and looped through that.

Steph

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.