Showing posts with label Copy. Show all posts
Showing posts with label Copy. Show all posts

COPY DATA FROM ONE FILE TO ANOTHER FILE USING C PROGRAM

How To COPY DATA FROM ONE FILE TO ANOTHER FILE USING C PROGRAM.


#include<stdio.h>
int main(){
  FILE *p,*q;
  char file1[20],file2[20];
  char ch;
  printf("\nEnter the source file name to be copied:");
  gets(file1);
  p=fopen(file1,"r");
  if(p==NULL){
      printf("cannot open %s",file1);
      exit(0);
  }
  printf("\nEnter the destination file name:");
  gets(file2);
  q=fopen(file2,"w");
  if(q==NULL){
      printf("cannot open %s",file2);
      exit(0);
  }
  while((ch=getc(p))!=EOF)
      putc(ch,q);
  printf("\nCOMPLETED");
  fclose(p);
  fclose(q);
 return 0;
}

C Program To Copy One Character Array Into Another

How to write a C Program To Copy One Character Array Into Another in C Programming Language ?

Solution For C Program :

/*C Program To Copy One Character Array Into Another.*/

#include<stdio.h>
void main()
{
char str1[81], str2[81];
int k = 0;
printf("\nEnter Any Data : ");
scanf("%s", str1);
printf ("\nProcessing The String : ");
for (k = 0; str1[k] != '\0'; k++)
str2[k] = str1[k];
str2[k] = '\0' ;
printf ("\nThe Two Stings Are :\n%s \t %s", str1, str2);
}


You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable

C Program/Code to Copies a BMP piece by piece

How to write a C Program/Code to Copies a BMP piece by piece in C Programming Language ?


Solution:
       
#include <stdio.h>
#include <stdlib.h>

#include "bmp.h"

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        printf("Usage: ./resize n infile outfile\n");
        return 1;
    }

    // remember filenames
    int n = atoi(argv[1]);
    char* infile = argv[2];
    char* outfile = argv[3];
    
    if (n < 1 || n > 100){
        printf("N must be between 1 and 100\n");
        return 1;
    }
 
    // open input file 
    FILE* inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        printf("Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE* outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || 
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }
    
    BITMAPINFOHEADER newbi;
    newbi.biWidth = bi.biWidth * n;
    newbi.biHeight = bi.biHeight * n;
    
    BITMAPFILEHEADER newbf;
    
    // determine padding for scanlines (old image)
    int padding =  (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    
    // determine padding for scanlines (new image)
    int newpadding = (4 - (newbi.biWidth * sizeof(RGBTRIPLE)) % 4) %4;
    
    newbi.biSizeImage = (newbi.biWidth * sizeof(RGBTRIPLE) + newpadding) * abs(newbi.biHeight);
    newbf.bfSize = newbi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
    
    // write outfile's BITMAPFILEHEADER
    fwrite(&newbf, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&newbi, sizeof(BITMAPINFOHEADER), 1, outptr);

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
    {
        // how many lines
        for (int l = 0; l < n; l++){
            
            // iterate over pixels in scanline
            for (int j = 0; j < bi.biWidth; j++)
            {
                // temporary storage
                RGBTRIPLE triple;
    
                // read RGB triple from infile
                fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
                
                for (int t = 0; t < n; t++){
                // write RGB triple to outfile
                fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
                }
                
            }
    
            // skip over padding, if any
            fseek(inptr, padding, SEEK_CUR);
    
            // then add it back (to demonstrate how)
            for (int k = 0; k < newpadding; k++)
            {
                fputc(0x00, outptr);
            }
        }
    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // that's all folks
    return 0;
}

Make a copy of file given in argv[1] to file given in argv[2]

How to write a C Program to Make a copy of file given in argv[1] to file given in argv[2] in C Programming Language ?

You have to use program with two arguments, the file names copy_from copy_to.

This C Program Make a copy of file given in argv[1] to file given in argv[2].

There is an access function with which we can see whether the file exists or not

 access(filename,F_OK);
 open 1. parameter= file name
 open 2. parameter for what we want to use the file
 O_RDONLY=only for reading,O_WRONLY-only for writing

There is errno variable in which there is the number of error --

 if (errno!=0) there is an error

The three parameter long version of open - it can create the file if it doesnt exist

there is a creat function as well - creat(filename,permissions);
O_TRUNC = if it existed, clear the content,
O_CREAT=create if it doesn't exist
3. parameter the permission, if it has to be created
S_IRUSR=permission for reading by the owner e.g.

Read gives back the number of bytes

    1. parameter the file descriptor
    2. parameter the address of variable, we read into
    3. parameter the number of bytes we want to read in

Write gives back the number of written bytes

      1. parameter the file descriptor
      2. parameter the address of variable we want to write out
      3. parameter the number of bytes we want to write out


Solution:

  1. //make a copy of file given in argv[1] to file given in argv[2]
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <fcntl.h> //open,creat
  5. #include <sys/types.h> //open
  6. #include <sys/stat.h>
  7. #include <errno.h> //perror, errno
  8. int main(int argc,char** argv){
  9.  if (argc!=3){perror("You have to use program with two arguments, the file names copy_from copy_to");exit(1);}
  10.  int f,g;
  11.  f=open(argv[1],O_RDONLY);
  12.  //there is an access function with which we can see whether the file exists or not
  13.  //access(filename,F_OK);
  14.  //open 1. parameter= file name
  15.  //open 2. parameter for what we want to use the file
  16.  //O_RDONLY=only for reading,O_WRONLY-only for writing
  17.  if (f<0){ perror("Error at opening the file\n");exit(1);}
  18.  //There is errno variable in which there is the number of error --
  19.  //if (errno!=0) there is an error
  20.  g=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
  21.  //the three parameter long version of open - it can create the file if it doesnt exist
  22.  //there is a creat function as well - creat(filename,permissions);
  23.  //O_TRUNC = if it existed, clear the content,
  24.  //O_CREAT=create if it doesn't exist
  25.  //3. parameter the permission, if it has to be created
  26.  //S_IRUSR=permission for reading by the owner e.g.
  27.  if (g<0){ perror("Error at opening the file\n");exit(1);}
  28.  char c;
  29.  while (read(f,&c,sizeof(c))){
  30.     //read gives back the number of bytes
  31.     //1. parameter the file descriptor
  32.     //2. parameter the address of variable, we read into
  33.     //3. parameter the number of bytes we want to read in
  34.     printf("%c",c); //we prints out the content of the file on the screen
  35.     if (write(g,&c,sizeof(c))!=sizeof(c))
  36.       {perror("There is a mistake in writing\n");exit(1);}
  37.       //write gives back the number of written bytes
  38.       //1. parameter the file descriptor
  39.       //2. parameter the address of variable we want to write out
  40.       //3. parameter the number of bytes we want to write out
  41.  }
  42.  close(f);
  43.  close(g);
  44.  return 0;
  45. }

C Program to copy a file to another file

How to write a C Program to copy a file to another file in C Programming Language ?

This C Program to copy a file to another file.

Solution:

  1. #include<stdio.h>
  2. void main()
  3. {
  4.         FILE *fp1,*fp2;
  5.         char ch;
  6.         char fname1[30],fname2[30];
  7.         printf("Enter the source file: ");
  8.         fflush(stdin);
  9.         scanf("%s",fname1);
  10.         printf("Enter the destination file: ");
  11.         fflush(stdin);
  12.         scanf("%s",fname2);
  13.         fp1=fopen(fname1,"r");
  14.         fp2=fopen(fname2,"w");
  15.         if(fp1==NULL)
  16.         {
  17.                 printf("\n cannot open file %s for reading",fname1);
  18.                 exit(1);
  19.         }
  20.         else if(fp2==NULL)
  21.         {
  22.                 printf("\n cannot open file %s for writing",fname2);
  23.                 exit(1);
  24.         }
  25.         else
  26.         {
  27.                 ch=getc(fp1);
  28.         while(ch!=EOF)
  29.         {
  30.                 putc(ch,fp2);
  31.                 ch=getc(fp1);
  32.         }
  33.         fclose(fp1);
  34.         fclose(fp2);
  35.         printf("\n files copied");
  36.         }
  37. }

A small I/O bound program to copy N bytes from an input file to an output file.

How to write a C Program : A small I/O bound program to copy N bytes from an input file to an output file. May read the input file multiple times if N is larger than the size of the input file in C Programming Language ?


  1. /*
  2.  * Description: A small i/o bound program to copy N bytes from an input
  3.  *              file to an output file. May read the input file multiple
  4.  *              times if N is larger than the size of the input file.
  5.  */
  6. /* Include Flags */
  7. #define _GNU_SOURCE
  8. /* System Includes */
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <string.h>
  15. #include <sys/types.h>
  16. #include <sys/stat.h>
  17. #include <sched.h>
  18. /* Local Defines */
  19. #define MAXFILENAMELENGTH 80
  20. #define DEFAULT_INPUTFILENAME "rwinput"
  21. #define DEFAULT_OUTPUTFILENAMEBASE "rwoutput"
  22. #define DEFAULT_BLOCKSIZE 1024
  23. #define DEFAULT_TRANSFERSIZE 1024*100
  24. int main(int argc, char* argv[]){
  25.         int i;
  26.     int rv;
  27.     int inputFD;
  28.     int outputFD;
  29.     int numProcesses;
  30.     char inputFilename[MAXFILENAMELENGTH];
  31.     char outputFilename[MAXFILENAMELENGTH];
  32.     char outputFilenameBase[MAXFILENAMELENGTH];
  33.     struct sched_param param;
  34.     ssize_t transfersize = 0;
  35.     ssize_t blocksize = 0;
  36.     char* transferBuffer = NULL;
  37.     ssize_t buffersize;
  38.     int policy;
  39.     ssize_t bytesRead = 0;
  40.     ssize_t totalBytesRead = 0;
  41.     int totalReads = 0;
  42.     ssize_t bytesWritten = 0;
  43.     ssize_t totalBytesWritten = 0;
  44.     int totalWrites = 0;
  45.     int inputFileResets = 0;
  46.     pid_t id;
  47.    
  48.     /* Process program arguments to select run-time parameters */
  49.     /* Set supplied transfer size or default if not supplied */
  50.     if(argc < 2){
  51.         transfersize = DEFAULT_TRANSFERSIZE;
  52.     }
  53.     else{
  54.         transfersize = atol(argv[1]);
  55.         if(transfersize < 1){
  56.             fprintf(stderr, "Bad transfersize value\n");
  57.             exit(EXIT_FAILURE);
  58.         }
  59.     }
  60.     /* Set supplied block size or default if not supplied */
  61.     if(argc < 3){
  62.         blocksize = DEFAULT_BLOCKSIZE;
  63.     }
  64.     else{
  65.         blocksize = atol(argv[2]);
  66.         if(blocksize < 1){
  67.             fprintf(stderr, "Bad blocksize value\n");
  68.             exit(EXIT_FAILURE);
  69.         }
  70.     }
  71.     /* Set supplied input filename or default if not supplied */
  72.     if(argc < 4){
  73.         if(strnlen(DEFAULT_INPUTFILENAME, MAXFILENAMELENGTH) >= MAXFILENAMELENGTH){
  74.             fprintf(stderr, "Default input filename too long\n");
  75.             exit(EXIT_FAILURE);
  76.         }
  77.         strncpy(inputFilename, DEFAULT_INPUTFILENAME, MAXFILENAMELENGTH);
  78.     }
  79.     else{
  80.         if(strnlen(argv[3], MAXFILENAMELENGTH) >= MAXFILENAMELENGTH){
  81.             fprintf(stderr, "Input filename too long\n");
  82.             exit(EXIT_FAILURE);
  83.         }
  84.         strncpy(inputFilename, argv[3], MAXFILENAMELENGTH);
  85.     }
  86.     /* Set supplied output filename base or default if not supplied */
  87.     if(argc < 5){
  88.         if(strnlen(DEFAULT_OUTPUTFILENAMEBASE, MAXFILENAMELENGTH) >= MAXFILENAMELENGTH){
  89.             fprintf(stderr, "Default output filename base too long\n");
  90.             exit(EXIT_FAILURE);
  91.         }
  92.         strncpy(outputFilenameBase, DEFAULT_OUTPUTFILENAMEBASE, MAXFILENAMELENGTH);
  93.     }
  94.     else{
  95.         if(strnlen(argv[4], MAXFILENAMELENGTH) >= MAXFILENAMELENGTH){
  96.             fprintf(stderr, "Output filename base is too long\n");
  97.             exit(EXIT_FAILURE);
  98.         }
  99.         strncpy(outputFilenameBase, argv[4], MAXFILENAMELENGTH);
  100.     }
  101.    
  102.     /* Set policy if supplied */
  103.     if(argc > 5){
  104.       if(!strcmp(argv[5], "SCHED_OTHER")){
  105.                 policy = SCHED_OTHER;
  106.                 printf("OTHER!\n");
  107.       }
  108.       else if(!strcmp(argv[5], "SCHED_FIFO")){
  109.                 policy = SCHED_FIFO;
  110.                 printf("FIFO!\n");
  111.       }
  112.       else if(!strcmp(argv[5], "SCHED_RR")){
  113.                 policy = SCHED_RR;
  114.                 printf("RR!\n");
  115.       }
  116.       else{
  117.                 fprintf(stderr, "Unhandeled scheduling policy\n");
  118.                 exit(EXIT_FAILURE);
  119.       }
  120.     }
  121.     else{
  122.         policy = SCHED_OTHER;
  123.     }
  124.     printf("argv[5] is: \n", argv[5]);
  125.     printf("policy is: %d\n", policy);
  126.         /* Set process to max prioty for given scheduler */
  127.     param.sched_priority = sched_get_priority_max(policy);
  128.    
  129.     /* Set new scheduler policy */
  130.     fprintf(stdout, "Current Scheduling Policy: %d\n", sched_getscheduler(0));
  131.     fprintf(stdout, "Setting Scheduling Policy to: %d\n", policy);
  132.     if(sched_setscheduler(0, policy, &param)){
  133.         perror("Error setting scheduler policy");
  134.         exit(EXIT_FAILURE);
  135.     }
  136.     fprintf(stdout, "New Scheduling Policy: %d\n", sched_getscheduler(0));
  137.     /* Set number of processes if supplied */
  138.     if(argc > 6){
  139.       numProcesses = atoi(argv[6]);
  140.       if(numProcesses <= 0){
  141.         fprintf(stderr, "Too few processes\n");
  142.         exit(EXIT_FAILURE);
  143.       }
  144.     }
  145.     else{
  146.         numProcesses = 1;
  147.     }
  148.     /* Confirm blocksize is multiple of and less than transfersize*/
  149.     if(blocksize > transfersize){
  150.         fprintf(stderr, "blocksize can not exceed transfersize\n");
  151.         exit(EXIT_FAILURE);
  152.     }
  153.     if(transfersize % blocksize){
  154.         fprintf(stderr, "blocksize must be multiple of transfersize\n");
  155.         exit(EXIT_FAILURE);
  156.     }
  157.     /* Allocate buffer space */
  158.     buffersize = blocksize;
  159.     if(!(transferBuffer = malloc(buffersize*sizeof(*transferBuffer)))){
  160.         perror("Failed to allocate transfer buffer");
  161.         exit(EXIT_FAILURE);
  162.     }
  163.         /* Set new scheduler policy */
  164. /*    fprintf(stdout, "Current Scheduling Policy: %d\n", sched_getscheduler(0));
  165.     fprintf(stdout, "Setting Scheduling Policy to: %d\n", policy);
  166.     if(sched_setscheduler(0, policy, &param)){
  167.     printf("sched_setscheduler(0, policy, &param) is:%d\n", sched_setscheduler(0, policy, &param));
  168.         perror("Error setting scheduler policy");
  169.         exit(EXIT_FAILURE);
  170.     }
  171.     fprintf(stdout, "New Scheduling Policy: %d\n", sched_getscheduler(0));
  172. */
  173.         for(= 0; i< numProcesses; i++){
  174.                 id = fork();
  175.                 printf("id is %d\n", id);
  176.                 if(id == 0){
  177.                     /* Open Input File Descriptor in Read Only mode */
  178.                     if((inputFD = open(inputFilename, O_RDONLY | O_SYNC)) < 0){
  179.                         perror("Failed to open input file");
  180.                         exit(EXIT_FAILURE);
  181.                     }
  182.                     /* Open Output File Descriptor in Write Only mode with standard permissions*/
  183.                     rv = snprintf(outputFilename, MAXFILENAMELENGTH, "%s-%d",
  184.                                   outputFilenameBase, getpid());    
  185.                     if(rv > MAXFILENAMELENGTH){
  186.                         fprintf(stderr, "Output filenmae length exceeds limit of %d characters.\n",
  187.                                 MAXFILENAMELENGTH);
  188.                         exit(EXIT_FAILURE);
  189.                     }
  190.                     else if(rv < 0){
  191.                         perror("Failed to generate output filename");
  192.                         exit(EXIT_FAILURE);
  193.                     }
  194.                     if((outputFD =
  195.                         open(outputFilename,
  196.                              O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
  197.                              S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) < 0){
  198.                                 perror("Failed to open output file");
  199.                                 exit(EXIT_FAILURE);
  200.                     }
  201.                     /* Print Status */
  202.                     fprintf(stdout, "Reading from %s and writing to %s\n",
  203.                             inputFilename, outputFilename);
  204.                         /* Read from input file and write to output file*/
  205.                     do{
  206.                                 /* Read transfersize bytes from input file*/
  207.                                 bytesRead = read(inputFD, transferBuffer, buffersize);
  208.                                 if(bytesRead < 0){
  209.                                     perror("Error reading input file");
  210.                                     exit(EXIT_FAILURE);
  211.                                 }
  212.                                 else{
  213.                                     totalBytesRead += bytesRead;
  214.                                     totalReads++;
  215.                                 }
  216.                                
  217.                                 /* If all bytes were read, write to output file*/
  218.                                 if(bytesRead == blocksize){
  219.                                     bytesWritten = write(outputFD, transferBuffer, bytesRead);
  220.                                     if(bytesWritten < 0){
  221.                                         perror("Error writing output file");
  222.                                         exit(EXIT_FAILURE);
  223.                                     }
  224.                                     else{
  225.                                         totalBytesWritten += bytesWritten;
  226.                                         totalWrites++;
  227.                                     }
  228.                                 }
  229.                                 /* Otherwise assume we have reached the end of the input file and reset */
  230.                                 else{
  231.                                     if(lseek(inputFD, 0, SEEK_SET)){
  232.                                         perror("Error resetting to beginning of file");
  233.                                         exit(EXIT_FAILURE);
  234.                                     }
  235.                                     inputFileResets++;
  236.                                 }
  237.                        
  238.                     }while(totalBytesWritten < transfersize);
  239.                     /* Output some possibly helpfull info to make it seem like we were doing stuff */
  240.                     fprintf(stdout, "Read:    %zd bytes in %d reads\n",
  241.                             totalBytesRead, totalReads);
  242.                     fprintf(stdout, "Written: %zd bytes in %d writes\n",
  243.                             totalBytesWritten, totalWrites);
  244.                     fprintf(stdout, "Read input file in %d pass%s\n",
  245.                             (inputFileResets + 1), (inputFileResets ? "es" : ""));
  246.                     fprintf(stdout, "Processed %zd bytes in blocks of %zd bytes\n",
  247.                             transfersize, blocksize);
  248.                    
  249.             /* Free Buffer */
  250.                     free(transferBuffer);
  251.                     /* Close Output File Descriptor */
  252.                     if(close(outputFD)){
  253.                         perror("Failed to close output file");
  254.                         exit(EXIT_FAILURE);
  255.                     }
  256.             /* Close Input File Descriptor */
  257.             if(close(inputFD)){
  258.                 perror("Failed to close input file");
  259.                 exit(EXIT_FAILURE);
  260.             }
  261.         break;
  262.         }
  263.         else if(id > 0){ //parent
  264.                 printf("Parent is %d\n", id);
  265.                 int status = 0;
  266.         waitpid(id, &status, 0);
  267.         }
  268.         else{ //error
  269.                 printf("Error. pid %d is negative\n", id );
  270.         }
  271.                 }
  272.     return EXIT_SUCCESS;
  273. }