Question

Need this in c programming

Question:


Many files on our computers, such as executables and many music and video files, are binary files (in contrast to text files). The bytes in these files must be interpreted in ways that depend on the file format. In this exercise, we write a program data-extract to extract integers from a file and save them to an output file. The format of the binary files in this exercise is very simple. The file stores n integers (of type int). Each integer consists of 4 bytes (in the native format on the Mimir platform). We number the integers in a file from 0 to n-1. So the first 4 bytes (bytes 0 to 3) are integer 0, the next 4 bytes (bytes 4 to 7) are integer 1, and so on. The size of the file is always a multiple of 4. A program data-gen is provided to generate binary files we can work on. It takes three arguments from the command line:seed, n, and filename. The program writes n pseudo-random numbers determined by seed to file filename. For example, the following command writes 100 integers to file a.dat. The 100 integers are random numbers determined by seed 3100. Please study the source code data-gen.c to learn how integers are written to the output file. $ ./data-gen 3100 100 a.dat The task of this exercise is to complete the code in data-extract.c. The program data-extract takes at least three command line arguments (as shown below), and extract integers from file input-file and saves the extracted integers to file output-file. $./data-extract input-file output-file range [range ..] The integers to be extracted from input-file are specified by ranges. A range can be two numbers separated by '-', like start-end, or a single number. start-end specifies integers starting from integer start to integer end. If a range is a single number pos, it specifies integer pos, which is the same as pos-pos. For example, the following command extract 10 integers from a.dat to t1.dat. The integers written to t1.dat are integers at indices 0, 1, 15, 16, 17, 18, 19, 1, 2, and 3 from a.dat. Note that an integer in a.dat can be extracted multiple times. $ ./data-extract a.dat t1.dat 0 1 15-19 1 2 3 If there are 100 integers in a.dat, the following command moves the integer at the beginning to the end. $ ./data-extract a.dat t2.dat 1-99 0 In the starter code, main() parses the command line arguments. The remaining tasks are as follows. 1. Add necessary statements in main() to open and close files properly (before and after the for loop). If any file operation fails, call my_error() to report error and exit. See comments in the starter code. 2. Complete the copy_integers() function, which has the following prototype. int copy_integers(FILE *outfp, FILE *infp, int start, int end); outfp is the outpot stream and infp is the input stream. The function copies integers start to end from infp to outfp. The function returns -1 on errors and 0 on success. Do not call my_error() in this function. Read the comments in the starter code for more implementation details. Some output files (*.dat) are provided. They are generated with the following commands. $ ./data-gen 3100 100 a.dat $ ./data-extract a.dat t1.dat 0 1 15-19 1 2 3 $ ./data-extract a.dat t2.dat 1-99 0 $ ./data-extract a.dat t3.dat 10 20 30 40 50 5 15 25 35 45 $ ./data-extract a.dat t4.dat 30-49 50-59 80-99 10-40 Some tools can help us to compare and examine binary files. Below are some examples. Lines that starts with '#' are comments explaining the following commands. See the manual pages for more options of cmp, xxd, and diff commands. # compare a.dat and b.dat $ cmp -b a.dat b.dat # compare a.dat and b.dat, and show detailed information $ cmp -bl a.dat b.dat # list groups of 4 bytes file a.dat in hexadecimal $ xxd -g4 a.dat # compare the hex dump of a.dat and b.dat $ diff <(xxd a.dat) <(xxd b.dat)


Datagen.c code:


#include <stdlib.h>

#include <stdio.h>


void my_error(char *s)

{

// print our own error message to standard error output

fprintf(stderr, "Error:%s\n", s);

// Use perror() to print the descriptive message about the error

perror("errno:");

exit(EXIT_FAILURE);

}


int main(int argc, char *argv[])

{

int n;

unsigned int seed;


if (argc != 4) {

fprintf(stderr, "Usage: %s <seed> <n> <filename>\n", argv[0]);

exit(EXIT_FAILURE);

}


// not checking the value of seed and n

seed = atoi(argv[1]);

n = atoi(argv[2]);

srand(seed);


// try to open the file specified on the command line

FILE *fp = fopen (argv[3], "w");


// check the return values!!

if (fp == NULL)

my_error("fopen() returned NULL.");


for (int i = 0; i < n; i ++) {

int r = rand(); // get a pseudo-random value


// write the integer to the file and check the return value!!

if (fwrite(&r, sizeof(r), 1, fp) != 1)

my_error("fwrite() failed");

}

fclose(fp);

return 0;

}


Data-extract skeleton code (fill in parts with TODO):


#include <stdlib.h>

#include <stdio.h>


void my_error(char *s)

{

// print our own error message to standard error output

fprintf(stderr, "Error:%s\n", s);

// Use perror() to print the descriptive message about the error

perror("errno");

exit(EXIT_FAILURE);

}


/* This function copy integers from file infp to file outfp.

* The integers copied are specified by start and end.  

*

* For example,

* start is 0, end is 0.

*      The first int in infp is copied to outfp.

* start is 10, end is 20.

*      11 integers are copied from infp to outfp, starting from integer 10.

*

* Functions that may be used in this function include

* fseek(), fread(), fwrite().

*

* Check the return values of function calls.

*

* Return values:

* 0:   success

* -1:  function calls failed

* */

int copy_integers(FILE *outfp, FILE *infp, int start, int end)

{

// TODO

return 0;

}


int main(int argc, char *argv[])

{

if (argc < 4) {

fprintf(stderr, "Usage: %s <input-filename> <output-filename> range [range ..]\n", argv[0]);

exit(EXIT_FAILURE);

}


FILE    *infp, *outfp;


// TODO

// open inputfile for read

// If it fails, call my_error("Cannot open input file.");

// open output for write

// If it fails, call my_error("Cannot open output file.");


for (int i = 3; i < argc; i ++) {

int start, end;


// example of using sscanf()

if (sscanf(argv[i], "%d-%d", &start, &end) != 2) {

if (sscanf(argv[i], "%d", &start) != 1)

my_error("Invalid range");

end = start;

}


if (start < 0 || end < 0 || end < start)

my_error("start and end must be >= 0 and start must be <= end");

if (copy_integers(outfp, infp, start, end))

my_error("copy_integers() reteurned a non-zero value.");

}


// TODO

// close files

// On error,

// call my_error("Cannot close input file.") or

//      my_error("Cannot close output file.")


return 0;

}



0 0
Add a comment Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 9 more requests to produce the answer.

1 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
Need this in c programming
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • need this in c programming and you can edit the code below. also give me screenshot...

    need this in c programming and you can edit the code below. also give me screenshot of the output #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINE_SIZE 1024 void my_error(char *s) { fprintf(stderr, "Error: %s\n", s); perror("errno"); exit(-1); } // This funciton prints lines (in a file) that contain string s. // assume all lines has at most (LINE_SIZE - 2) ASCII characters. // // Functions that may be called in this function: // fopen(), fclose(), fgets(), fputs(),...

  • C Language Programming. Using the program below - When executing on the command line only this...

    C Language Programming. Using the program below - When executing on the command line only this program name, the program will accept keyboard input and display such until the user does control+break to exit the program. The new code should within only this case situation “if (argc == 1){ /* no args; copy standard input */” Replace line #20 “filecopy(stdin, stdout);” with new code. Open read a text file “7NoInputFileResponse.txt” that contains a message “There were no arguments on the...

  • #include <stdlib.h> #include <stdio.h> #include "main.h" #define MAX_NUM_LENGTH 11 void usage(int argc, char** argv) { if(argc...

    #include <stdlib.h> #include <stdio.h> #include "main.h" #define MAX_NUM_LENGTH 11 void usage(int argc, char** argv) { if(argc < 4) { fprintf(stderr, "usage: %s <input file 1> <input file 2> <output file>\n", argv[0]); exit(EXIT_FAILURE); } } /* This function takes in the two input file names (stored in argv) and determines the number of integers in each file. If the two files both have N integers, return N, otherwise return -1. If one or both of the files do not exist, it...

  • Below is a basic implementation of the Linux command "cat". This command is used to print...

    Below is a basic implementation of the Linux command "cat". This command is used to print the contents of a file on the console/terminal window. #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) {FILE *fp; if(2 != argc) {priritf ("Usage: cat <filename>\n"); exit(1);} if ((fp = fopen(argv[1], "r")) == NULL) {fprintf (stderr, "Can't. open input file %s\n", argv[1]); exit (1);} char buffer[256]; while (fgets(X, 256, fp) != NULL) fprintf(Y, "%s", buffer); fclose(Z); return 0;} Which one of the following...

  • Run the code in Linux and provide the screenshot of the output and input #include <signal.h>...

    Run the code in Linux and provide the screenshot of the output and input #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> static void cleanup(); static void docleanup(int signum); static const char *SERVER_ADDR = "127.0.0.1"; static const int SERVER_PORT = 61234; static int cfd = -1; int main(int argc, char *argv[]) { struct sockaddr_in saddr; char buf[128]; int bufsize = 128, bytesread; struct sigaction sigact; printf("client starts running ...\n"); atexit(cleanup); sigact.sa_handler =...

  • Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h>...

    Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h> #define SIZE (10) typedef struct _debugLab { int i; char c; } debugLab; // Prototypes void PrintUsage(char *); void DebugOption1(void); void DebugOption2(void); int main(int argc, char **argv) { int option = 0; if (argc == 1) { PrintUsage(argv[0]); exit(0); } option = atoi(argv[1]); if (option == 1) { DebugOption1(); } else if (option == 2) { DebugOption2(); } else { PrintUsage(argv[0]); exit(0); } }...

  • C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in...

    C programming help! /* Your challenge is to format the following code in a readable manner, anwsering the questions in the comments. * */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <strings.h> #define BUFFERT 512 #define BACKLOG 1 int create_server_socket (int port); struct sockaddr_in sock_serv,sock_clt; int main(int argc, char** argv){ int sfd, fd; unsigned int length = sizeof(struct sockaddr_in); long int n, m, count...

  • Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically...

    Assume I don't understand C++ Can someone explain this program to me Line by Line? Basically what each line actually does? whats the function? whats the point? Don't tell me what the program does as a whole, I need to understand what each line does in this program. #include #include #include #include #include #define SERVER_PORT 5432 #define MAX_LINE 256 int main(int argc, char * argv[]) {    FILE *fp;    struct hostent *hp;    struct sockaddr_in sin;    char *host;...

  • In C using the following 2 files to create a 3rd file that uses multiple threads...

    In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...

  • My question is listed the below please any help this assignment ; There is a skeleton...

    My question is listed the below please any help this assignment ; There is a skeleton code:  copy_file_01.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char ch ; FILE *source , *target;    if(argc != 3){ printf ("Usage: copy file1 file2"); exit(EXIT_FAILURE); } source = fopen(argv[1], "r"); if (source == NULL) { printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } target = fopen(argv[2], "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT