Dear respected programmers. Please could you help me (again) on how to put the following code into functions for my program. I have read on-line and understand how functions work but when I do it myself it all goes pear shaped(I am such a noob). Please could you help with how to for example to write the code below into functions.(like opening the input file).

My attempt:

void outputFile(int argc, char **argv)

{
/* Check that the output file doesnt exist */

if (stat(argv[argc-1], &inode) != -1)

{
    printf("Warning: The file %s already exists. Not going to overwrite\n", argv[argc-1]); 
    return -1;
}
/*Opening ouput files*/

file_desc_out = open(argv[i],O_CREAT | O_WRONLY | O_EXCL , S_IRUSR|S_IWUSR);
if(file_desc_out == -1)
{
    printf("Error: %s cannot be opened. \n",argv[i]);               //insted of argv[2] have pointer i. 
    return -1;
}

}

Any help on how I would now reference to this in my program is appreciated thank you. I tried: ouputfile(but I cant figure out what goes here and why either).

Recommended Answers

All 4 Replies

I have a better idea. How about you show us your attempts at writing functions and we can show you where you went wrong? Otherwise you're essentially asking for a full tutorial on how to write functions, which most of us aren't inclined to write.

Ok thanks I will just post it.

I have a better idea. How about you show us your attempts at writing functions and we can show you where you went wrong? Otherwise you're essentially asking for a full tutorial on how to write functions, which most of us aren't inclined to write.

sorry I edited my post, I hope that helps.

Few problems here.
1. Design problems.
1.1 You declare the function as void, yet in some cases return a value. Make up your mind (should I write a function like this, I'd declare it int and return the file descriptor).
1.2 The function opens just one file; therefore it needs just one argument. Yet you pass it the whole (counted) array of them.
That is, the proper declaration should be

int outputFile(char * filename)

2. Implementation problems.
2.1 A stat/open combination is a race condition (imagine another process creating the file right in between of a (successful) call to stat and a call to open). Don't do that.
Besides, it is redundant, because O_CREAT | O_EXCL flags do force open to fail if the file exists.
2.2 Error message at line 17 is not informative.

3. Too many unnecessary (and even undeclared) variables. What is inode, what is i?

All that said, the function becomes

int outputFile(char * filename)
{
    int file_desc_out = open(filename, O_CREAT | O_WRONLY | O_EXCL , S_IRUSR|S_IWUSR);
    if (file_desc_out == -1) {
        perror(filename);
    }
    return file_desc_out;
}
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.