Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

C and Linux Programming, Urgent!

crash21crash21 Member Posts: 2
Hello,

I have to make in my C program a new file called tempfile.txt inside a temp folder.
Now I am in home directory.
Temp folder is under home directory.
How can I create the file and write inside it a phrase like "demo" and after close it???
I have tried execl ("/bin/", "pico", "temp", (char *)0); but don't work of course... I can't find an editor to use inside bin...
I don't know what to do... It's my first time use C in Linux...
Please help me ASAP.

Comments

  • nugentnugent Member Posts: 87
    to create a directory you need to use the mkdir() function:
    [code]
    #include
    #include
    #include

    int main()
    {
    // the folder name
    char *dir_name = "temp_folder";

    // this is the mode (read, write and execute for the file owner
    mode_t dir_mode = S_IRWXU;

    // attempt to make the directory
    int ret = mkdir(dir_name, dir_mode);

    // check if mkdir() failed
    if(ret == -1)
    printf("Error creating directory
    ");
    else
    printf("Success
    ");

    return 0;
    }
    [/code]

    this code will write to a file, it will create the file if it doesn't exist. if the file does exist and has content it will be over written (all content in the file will be LOST)
    [code]
    #include

    int main()
    {
    FILE *fp;
    // This is the name of the file to open
    char *filename = "tempfile.txt";

    // open the file for writing (and check if opened successfully)
    if( (fp = fopen(filename, "w")) == NULL)
    {
    // if we failed to open the file
    printf("Failed to open file
    ");
    return 1;
    }

    // we succeed in opening file, now write to lines
    fputs("demo line 1
    ", fp);
    fputs("demo line 2
    ", fp);

    // close file
    fclose(fp);

    return 0;
    }
    [/code]

    For more information check out the GNU libc manual:
    http://www.gnu.org/software/libc/manual/html_node/index.html

    specifically look at the "I/O on Streams" and "File System Interface" chapters

    ------
    nugent



  • kumar00kumar00 Member Posts: 1
    : Hello,
    :
    : I have to make in my C program a new file called tempfile.txt inside a temp folder.
    : Now I am in home directory.
    : Temp folder is under home directory.
    : How can I create the file and write inside it a phrase like "demo" and after close it???
    : I have tried execl ("/bin/", "pico", "temp", (char *)0); but don't work of course... I can't find an editor to use inside bin...
    : I don't know what to do... It's my first time use C in Linux...
    : Please help me ASAP.
    :

Sign In or Register to comment.