What is the use of `putw` and `getw` function in c?

后端 未结 4 507
无人及你
无人及你 2020-12-06 08:49

I wanna know the use of putw() and getw() function. As I know, these are used to write and read from file as like as putc and ge

4条回答
  •  悲&欢浪女
    2020-12-06 09:29

    Let's read the point to point explanation of getw() and putw() functions.

    • getw() and putw() are related to FILE handling.
    • putw() is use to write integer data on the file (text file).
    • getw() is use to read the integer data from the file.
    • getw() and putw() are similar to getc() and putc(). The only difference is that getw() and putw() are especially meant for reading and writing the integer data.

    int putw(integer, FILE*);
    

    Return type of the function is integer.

    Having two argument first "integer", telling the integer you want to write on the file and second argument "FILE*" telling the location of the file in which the data would be get written.

    Now let's see an example.

    int main()
    {
        FILE *fp;
    
        fp=fopen("file1.txt","w");
        putw(65,fp);
    
        fclose(fp);
    }
    

    Here putw() takes the integer number as argument (65 in this case) to write it on the file file1.txt, but if we manually open the text file we find 'A' written on the file. It means that putw() actually take integer argument but write it as character on the file.

    So, it means that compiler take the argument as the ASCII code of the particular character and write the character on the text file.


    int getw(FILE*);
    

    Return type is integer.

    Having one argument that is FILE* that is the location of the file from which the integer data to be read.

    In this below example we will read the data that we have written on the file named file1.txt in the example above.

    int main()
    {
      FILE *fp;
      int ch;
    
      fp=fopen("file1.txt","r");
    
      ch=getw(fp);
      printf("%d",ch);
    
      fclose(fp);
    }
    

    output

    65
    

    Explanation: Here we read the data we wrote to file1.txt in above program and we will get the output as 65.

    So, getw() reads the character 'A' that was already written on the file file1.txt and return the ASCII code of the character 'A' that is 65.

    We can also write the above program as:

    int main()
    {
       FILE *fp;
    
       fp=fopen("file1.txt","r");
    
       printf("%d",getw(fp));
    
      fclose(fp);
    }
    

    output

    65
    

提交回复
热议问题