开发者

SImple C Program opening a file

I'm trying to make a program to open a file, called "write.txt".

#include <stdio.h>

main() {
    FILE *fp;
    fp = fopen("write.txt", "w");
    return 开发者_开发百科0;
 }

Should this work? Because it returns nothing.


Other than an old variant of main, there's not really much wrong with that code. It should, barring errors, create the file.

However, since you're not checking the return value from fopen, you may get an error of some sort and not know about it.

I'd start with:

#include <stdio.h>
#include <errno.h>
int main (void) {
    FILE *fp;
    fp = fopen ("write.txt","w");
    if (fp == NULL) {
        printf ("File not created okay, errno = %d\n", errno);
        return 1;
    }
    //fprintf (fp, "Hello, there.\n"); // if you want something in the file.
    fclose (fp);
    printf ("File created okay\n");
    return 0;
}

If you're adamant that the file isn't being created but the above code says it is, then you may be a victim of the dreaded "IDE is working in a different directory from what you think" syndrome :-)

Some IDEs (such as Visual Studio) will actually run your code while they're in a directory like <solution-name>\bin or <solution-name>\debug. You can find out by putting:

system ("cd"); // for Windows
system ("pwd") // for UNIXy systems

in to your code to see where it's running. That's where a file will be created if you specify a relative path line "write.txt". Otherwise, you can specify an absolute path to ensure it tries to create it at a specific point in the file system.


What did you expect it to 'return' - it opens a file, on most platforms creating one if it doesn't exist.

You should probably fclose(fp) the file at the end.


I think you want to print the contents of file write.txt. (Assume it contains characters).

#include <stdio.h>

int main()
{             

    FILE *fp,char ch;

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

    if(fp==NULL)
    {
        printf("Some problem in opening the file");
        exit(0);
    } 
    else
    { 
        while((ch=fgetc(fp))!=EOF)
        {
            printf("%c",ch);
        }
    }

    fclose(fp);

    return 0;  
}


I think you should study some more fundamentals in C before you start attempting to work with files. A return means some data is passed back to the calling code from the called function.In this case you return 0 at the end of your program. You did not do anything with your FILE pointer except cause a new file to be created...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜