write a file:

#include<iostream>
using namespace std;
int main()
{
    FILE *fp;
    fp=fopen("e:\\myfiles\\sample.txt","w");

   //Check permission if you can write a file
    if(!fp)
    {
           cout << "cannot open file.\n";
           system("pause");
           exit(1);
    }
    //prints the character ASCII from 65 to 90 (A-Z) to a file
    for(int i=65; i<91; i++)
            fputc(i,fp);

    fclose(fp);
    return 0;

}

Guys can you explain this to me... I don't know how it works. but when i run it to my computer it works

The most correct way to actually test for file write permission is to attempt to write to the file. The reason for this is because different platforms expose write permissions in very different ways. Even worse, just because the operating system tells you that you can (or cannot) write to a file, it might actually be lying, for instance, on a unix system, the file modes might allow writing, but the file is on read only media, or conversely, the file might actually be a character device created by the kernel for the processes' own use, so even though its filemodes are set to all zeroes, the kernel allows that process (and only that process) to muck with it all it likes.

Here is your codes with comments at each step

    #include<iostream>
    using namespace std;
    int main()
    {
        FILE *fp;   // this ia a file pointer used to make changes to the file
        fp=fopen("e:\\myfiles\\sample.txt","w");   // here, you are giving the pointer your file location
       //Check permission if you can write a file
        if(!fp) // !fp means 0 ( permission to access file denied)
        {
               cout << "cannot open file.\n";
               system("pause");
               exit(1);
        }
        //prints the character ASCII from 65 to 90 (A-Z) to a file
        for(int i=65; i<91; i++)
                fputc(i,fp);   // fputc is used to write a character to a file, hence its name
        fclose(fp);  // all files opened need to be closed 
        return 0;
    }

By closing the file, you release the system resources used by the file, so it's important to close a file when you are done.

Edited 1 Year Ago by mridul.ahuja

This article has been dead for over six months. Start a new discussion instead.