is it possible to copy specificity from a file for example i want to copy x number of bytes from x position to x position?

Recommended Answers

All 3 Replies

Yes its possible, try googling fseek, ftell, fopen.

#include<stdio.h>
#include<stdlib.h>
int main ()
{
FILE *pFile;
FILE *copy;
FILE *originalcp;
FILE *create_cp;
size_t n;
unsigned char buffer[356];
pFile = fopen ( "myfile.txt" , "w+b" );
fputs ( "This is a test." , pFile );
fseek (pFile, 0, SEEK_END);
long size=ftell (pFile);
printf(" file: %ld,\n",size);
fseek (pFile,0, SEEK_END);
fputs( "hello my name is",pFile); 
fseek (pFile,0, SEEK_END);
size=ftell (pFile);
printf(" file: %ld,\n",size);
fclose ( pFile );


create_cp = fopen( "myfilecopy.txt","a+b"); 
pFile = fopen ( "myfile.txt" , "r+b" );
originalcp = fopen ("myfile.txt", "a+b");
copy = fopen ( "myfilecopy.txt", "w+b");

		while (( n = fread(buffer,1,sizeof buffer, originalcp)) > 0)
		{
		fwrite(buffer,1, n , copy);
	}
if((originalcp !=NULL) && (copy != NULL))
		{
			
		fclose(originalcp);
		fclose(copy);
		
		fclose(create_cp);
		printf("done..... ");
		}			

		if (originalcp == NULL)
		{
		puts("unable to open original file\n");
		}
		if (copy == NULL)
		{
		puts("unabe to open copiedied file");
		return 1; 
	
}
}

i cant seem to find away to copy just the "hello my name is" part from "myfile.txt"

Will an example help?

#include <stdio.h>
#include <string.h>

void dump_file(FILE *in, FILE *out)
{
    int byte;

    while ((byte = getc(in)) != EOF)
        putc(byte, out);
}

int main(void)
{
    /* Use binary if you want to seek arbitrarily */
    FILE *in = fopen("test.txt", "rb");

    if (in != NULL) {
        long size;

        /* Not strictly portable, but it works */
        fseek(in, 0, SEEK_END);
        size = ftell(in);
        rewind(in);

        printf("File size: %ld\n", size);

        for (;;) {
            char cmd[512];
            long offset;

            fputs("> ", stdout);
            fflush(stdout);

            if (scanf("%511s", cmd) != 1)
                break;

            if (strcmp(cmd, "dump") == 0)
                dump_file(in, stdout);
            else if (strcmp(cmd, "jump") == 0 && scanf("%d", &offset) == 1) {
                if (offset < 0 || offset >= size)
                    fputs("Offset out of range\n", stderr);
                else {
                    clearerr(in);
                    fseek(in, offset, SEEK_SET);
                }
            }
            else if (strcmp(cmd, "exit") == 0)
                break;
            else
                fputs("Invalid command\n", stderr);
        }

        fclose(in);
    }

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.