abhi abhi
abhi abhi

Reputation: 181

File I/O management in C

My first post :), am starting out with C language as basic learning step into programming arena. I am using following code which reads string from text file, makes directory with that string name and opens a file for writing in that created directory. But am not able to create a file inside directory made, here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <string.h>

int main()
{
    char file_name[25], cwd[100];
    FILE *fp, *op;

    fp = fopen("myfile.txt", "r");

    if (fp == NULL)
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    fgets(file_name, 25, fp);

    _mkdir(file_name);

       if (_getcwd(cwd,sizeof(cwd)) != 0) 
    {
      fprintf(stdout, "Your dir name: %s\\%s\n", cwd,file_name);

        op = fopen("cwd\\file_name\\mynewfile.txt","w");
        fclose(op);
    }
    fclose(fp);
    return 0;
}

Upvotes: 3

Views: 193

Answers (4)

everclear
everclear

Reputation: 332

I see you are using the return values. That is a good start for a beginner. You can refine your error messages by including "errno.h". Instead of printing your own error messages call

printf("%s", strerror(errno));

You get more precise error messages that way.

Upvotes: 1

Scy
Scy

Reputation: 498

use

#include <sys/stat.h>
#include <sys/types.h>

instead of

#include <direct.h>

and modify

op = fopen("cwd\\file_name\\mynewfile.txt","w”);

Upvotes: 2

uba
uba

Reputation: 2031

What you need is to store the file name (with the path) in a c-string before opening. What you are opening is cwd\file_name\mynewfile.txt. I doubt that your directory is named cwd. A sample could could be:

char file_path[150];
sprintf(file_path, "%s\\%s\\mynewfile.txt", cwd, file_name);
op = fopen(file_path,"w");

Upvotes: 2

eyebrowsoffire
eyebrowsoffire

Reputation: 947

op = fopen("cwd\\file_name\\mynewfile.txt","w”);

You’re actually passing the string literals “cwd” and “file_name” as part of the path of the file, when I think you actually mean to put the contents of the variables with those names in there. You will probably have to piece together a string for the path. Try looking into strcat()

http://www.cplusplus.com/reference/cstring/strcat/

Upvotes: 0

Related Questions