Basically I'm combining two binaries using the "cat" command on Linux.
And I want to be able to separate them again using C
this is the code I got so far
int main(int argc, char *argv[]) {
// Getting this file
FILE *localFile = fopen(argv[0], "rb");
// Naming a new file to save our carved binary
FILE *newFile = fopen(argv[1], "wb+");
// Moving the cursor to the offset: 19672 which is the size of this file
fseek(localFile, 19672, SEEK_SET);
// Copying to the new file
char ch;
while ( ( ch = fgetc(localFile) ) != EOF ) {
fputc(ch, newFile);
}
}
Assuming that you already know where the second file starts. You can proceed as follows. (This is bare minimal)
#include <stdio.h>
#include <unistd.h>
int main()
{
FILE* f1 = fopen("f1.bin", "r");
FILE* f2 = fopen("f2.bin", "w");
long file1_size = 1;
lseek(fileno(f1), file1_size, SEEK_SET);
char fbuf[100];
int rd_status;
for( ; ; ) {
rd_status = read(fileno(f1), fbuf, sizeof(fbuf));
if (rd_status <= 0)
break;
write(fileno(f2), fbuf, rd_status);
}
fclose(f1);
fclose(f2);
return 0;
}
Input File -- f1.bin
1F 2A
Output File -- f2.bin
2A
Please, modify the file names and file sizes according to your example.
Related
C.
bad file descriptor error by working on files.
This is an assignment for college. I need to compress file txt and then to uncompress it. The compress method working fine
and it compresses by the idea that the last binary digit (Msb) is zero always in any ASCII char.
Does anybody know why it happens?
The problem happens when I do fgetc(input_file_8to7) in the uncompress method
The mainly problem is that i get -1 from the 2 fgetc(input_file_8to7) in uncompresd method
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdint.h>
the input for the uncompress is the output of the compress , the input is txt file that conatain the next 2 lines:
A hex dump is a hexadecimal view of computer data, from memory or from a computer file.
***compres method***
void compress8to7(FILE *input,FILE* output8to7)
{
// 0x00 87 00 87 00 87 00 87 ll
uint64_t magic=0x87008700870087ll;
uint64_t inputsize=0;
fwrite(&magic,sizeof (magic),1,output8to7);
fwrite(&inputsize,sizeof(inputsize),1,output8to7);
unsigned char st;
unsigned char st2;
char check;
char check2;
char shift=7;
char shift_st=0;
unsigned char inbfile;
// will contain the resullt of the asked new binary lines comprees
int breakflag=0;
int breakflag2=0;
int cnt=-1;
//this parameter will help to know when we dont need to move 1 back in
the pointer of input file
while(1) {
cnt++;
if (ftell(input)>1 && cnt%7!=0) //
{
fseek(input,-1 ,SEEK_CUR) ;
}
check = fgetc(input);
st=check;
if(check2==EOF){breakflag2=1;}
check2 = fgetc(input);
> //if the length is odd number check2 will get the eof
st2=check2;
if(check==EOF){breakflag=1;}
st2=st2<<shift;
> //move the digit to the right position
bit manipulation
st=st>>shift_st;
shift_st++;
if(shift_st==7)
{shift_st=0;}
shift=shift-1;
if(shift==0)
shift=7;
if(breakflag2!=1)
{inbfile=st2|st;
}else{ inbfile=st; }
fwrite(&inbfile, sizeof(inbfile),1,output8to7);
write to the file
if(feof(input))
{
inputsize= ftell(input);
fseek(output8to7,8,SEEK_SET);
fwrite(&inputsize,sizeof (inputsize),1,output8to7);
// if(breakflag==1)
break;}
}
}
*** uncompress method***
the problem is in this method
void uncompress8to7 (FILE *input_file_8to7 ,FILE *output_file_txt){
char st;
char st2;
char check;
char check2;
char shift2 = 7;
char shift_st = 0;
char shift_helper=7;
char shift_helper2=6;
char sthelper;
char sthelper2;
char inbfile; // will contain the resullt of the asked new binary lines comprees
int breakflag = 0;
int breakflag2 = 0;
int cnt = -1;//this parameter will help to know when we dont need to move 1 back in the pointer of input file
rewind(input_file_8to7);
printf("%d",ftell(input_file_8to7));
fseek(input_file_8to7,16,SEEK_SET);
printf("\n%d",ftell(input_file_8to7));
int a=0;
while(1) {
cnt++;
if(cnt>1) //
{fseek(input_file_8to7,-1 ,SEEK_CUR);}
printf("\n%d",ftell(input_file_8to7));
from that fgetc i get the bad file descriptor erorr
check = fgetc(input_file_8to7);
if(ferror(input_file_8to7)){
perror("eror by perror");
printf("file erorr");}
// printf("\n%d",ftell(input_file_8to7));
st = check;
check2 = fgetc(input_file_8to7);
st2 = check2;
if(cnt<2)
fseek(input_file_8to7,0,SEEK_SET);
if(check2==EOF){
breakflag2 = 1;
}
sthelper2=st2;
sthelper2=sthelper2>>shift_helper2;
st2=st2<<shift2;
st2=st2>>shift2;
sthelper=st;
sthelper=sthelper>>shift_helper;
sthelper=shift_helper<<shift_helper-1;
st=st<<shift_st;// to make all zero after the msb
st=st>>shift_st;// to make all zero after the msb
shift_helper2--;
if(shift_helper==-1)
{shift_helper2=6;}
shift_helper--;
if(shift_helper==-1){
shift_helper=7;
}
shift_st++;
if(shift_st==7)
{shift_st=0;}
shift2=shift2-1;
if(shift2==0)
shift2=7;
if(breakflag2==1)
{break;}
if(cnt%7==0){
inbfile=st;
}else{
inbfile=sthelper|st2;
}
writing to the file
fwrite(&inbfile,sizeof(inbfile),1,output_file_txt);
break the loop when we got to the end of file
if(feof(input_file_8to7))
{ break;}
}
}
***main***
int main(int argc, char **argv) {
char* input=NULL;
char* output8to7=NULL;
input=argv[1];
output8to7=argv[2];
open files
FILE* inputfile = fopen(input, "r");
if(inputfile==NULL)
{
printf("couldnt open input file ");
exit(-1);
}
FILE* file8to7=fopen(output8to7, "wb");
if(file8to7==NULL)
{
printf("couldnt open output file");
printf(output8to7);
exit(-1);
}
compress
compress8to7(inputfile,file8to7);
FILE* file8to7input=fopen("exampleout.bin", "ab");
FILE* output_file=fopen("UNoutput_file2.txt", "wb");
if(output_file==NULL)
{printf("couldnt open output file");
exit(-1);
}
uncompress8to7(file8to7input,output_file);
fclose(output_file);
fclose(file8to7input);
fclose(inputfile);
fclose(file8to7);
return 0;
}
This is the code to open the file:
FILE* file8to7input=fopen("exampleout.bin", "ab");
This opens it as an output file in append mode. You're trying to read from it in the uncompress8to7() function. You need to open it as in input file in read mode. Change that line to:
FILE* file8to7input=fopen("exampleout.bin", "rb");
This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}
I've designed a function in C that takes two files, XORs the contents of the first file with a 10 byte key and puts the result in a separate file. My program is based on enhancing LSB stenography using encryption. The XOR function mentioned above is meant to encrypt the plain text file and generate the cipher text file. The generated cipher text file is then used by another function which encodes it into the image. In this instance the XOR function works as intended, but the problem occurs during decoding. I've designed my program to decode the data from the image and place it in a text file (this will contain the cipher text previously encoded). Now when I use the same XOR function to decrypt the cipher text into plain text in the decoding phase, nothing but the print statements get executed in the function. The program logic is sound as I've tested the logic using a standalone program.
include contains all the function prototypes and the header files required for execution.
XOR Function:
#include<header.h>
void enc(FILE *source, FILE *destination)
{
char text_buff, key[11];
int i;
printf("\nenter the key (max lenght 10): ");
for(i = 0; ((key[i] = getchar()) != '\n'); i++);
key[i] = '\0';
char new;
printf("\nThe string obtained: \t");
i = 0;
while((text_buff = fgetc(source)) != EOF)
{
new = text_buff ^ key[i];
fputc(new, destination);
i++;
printf("%c",new);
if(i==10)
i=0;
}
printf("\nsuccessful\n");
}
Main function:
#include <header.h>
int main(int argc, char *argv[])
{
//declaring variables and file pointers
char *option = argv[1];
FILE *source; //source bmp image
FILE *secretfile; //secret text file
FILE *newbmp; //new bmp image
FILE *secretmsg; //decrypted data text file
FILE *plain_text; //Plain text1
FILE *result_text; //Plain text2
//encode operations
if(argc == 6)
{
//if argument passed is '-e'
if(!strcmp(option, "-e"))
{
if((plain_text = fopen(argv[2], "r")) == NULL)
{
FILE_ERROR(argv[2]);
EXIT;
}
if((source = fopen(argv[3], "r")) == NULL)
{
FILE_ERROR(argv[3]);
EXIT;
}
if((secretfile = fopen(argv[4], "r+")) == NULL)
{
FILE_ERROR(argv[4]);
EXIT;
}
if((newbmp = fopen(argv[5], "w")) == NULL)
{
FILE_ERROR(argv[5]);
EXIT;
}
enc(plain_text,secretfile);
encodeImg(source, secretfile, newbmp);
}
else
{
INVALID_ARGUMENTS;
EXIT;
}
}
//decode operations
else if(argc == 5)
{
//if argument passed is '-d'
if(!strcmp(option, "-d"))
{
if((newbmp = fopen(argv[2], "r")) == NULL)
{
FILE_ERROR(argv[2]);
EXIT;
}
if((secretmsg = fopen(argv[3], "r+")) == NULL)
{
FILE_ERROR(argv[3]);
EXIT;
}
if((result_text = fopen(argv[4], "w")) == NULL)
{
FILE_ERROR(argv[4]);
EXIT;
}
decodeimg(newbmp, secretmsg);
enc(secretmsg,result_text);
fclose(secretmsg);
fclose(result_text);
}
else
{
INVALID_ARGUMENTS;
EXIT;
}
}
//if no other argument is passed
else
{
INVALID_ARGUMENTS;
EXIT;
}
}
Header file contents:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include "errorHandle.c"
//encode image main function
void encodeImg(FILE *source, FILE *secretfile, FILE *newbmp);
//size of image file(called from encodeImg)
int sizeImgFile(FILE *s1);
//size secret text file(called from encodeImg)
int sizeTxtFile(FILE *s2);
//string encode(called from encodeImg)
void stringEncode(char *String, FILE *source, FILE *newbmp);
//get character bits(called from stringEncode)
int get_bit(char byte, int bit);
//size encode(called from encodeImg)
void sizeEncode(int val, FILE *source, FILE *newbmp);
//secret encode(called from encodeImg)
void secretEncode(FILE *source, FILE *secretfile, FILE *newbmp);
//decode image main function
void decodeimg(FILE *newbmp, FILE *secretmsg);
//size decode(called from decodeimg)
void sizeDcp(FILE *newbmp, int *size);
//string decode(called from decodeimg)
void strDcp(FILE *newbmp, char *str, int size);
//secret decode(called from decodeimg)
void secretDcp(FILE *newbmp, FILE *secretmsg, int secretSize);
//Xor encryption(called from xor)
void enc(FILE *source, FILE *destination);
#define INVALID_ARGUMENTS printf("./a.out: missing file(s) operand\nTry - ./a.out <-e or -d> <plain text> <source bmp image> <secret text file> <new bmp image>\n")
#define EXIT exit(1)
#define FILE_ERROR(file_name) printf("couldn't open file: %s\n", file_name)
#define FILE_SIZE_ERROR printf("cannot perform operation: size of secret message is greater than the imagefile\n")
while((text_buff = fgetc(source)) != EOF)
The fgetc function returns an int. But you chop it to a char, assign that to text_buff, and then compare that to EOF. That won't work. You are supposed to compare the return value of fgetc to EOF, not any other value.
There are two possibilities. Either some value of char maps to EOF or no value of char maps to EOF. If some value of char maps to EOF, then when you read that character in the middle of the file, you'll treat at as the end of the file. If no value of char maps to EOF, then you'll never detect the end of the file.
So this can't possibly work right.
I want to check if there are any duplicates in a .txt file. I've wrote a code but it's not running. I'm not sure about opening the norep.txt file in "a+" mode. The idea is to put the first word of my text in the norep.txt file, then compare every word in the text.txt with the words in norep.txt and copy only the words I need in the file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fd;
FILE *ft;
char aux[30];
char aux1[30];
int len;
fd = fopen("c:\\text.txt", "r");
if (fd == NULL) {
puts("Error");
}
ft = fopen("c:\\norep.txt", "a+");
if (ft == NULL) {
puts("Error");
}
fscanf(fd, "%s", aux);
fprintf(ft, "%s", aux);
rewind(fd);
rewind(ft);
while (!feof(fd)) {
fscanf(fd, "%s", aux);
while (!feof(ft)) {
fscanf(ft, "%s", aux1);
len = strcmp(aux, aux1);
if (len != 0) {
fprintf(ft, "%s", aux);
}
}
rewind(ft);
}
return 0;
}
You should flush the output file before you rewind it.
fflush - flush a stream or fflush
Of course, this will not fix your problem because:
Note below that the manual says that reposition operations are ignored so that your attempt to read will always find the end of file.
append: Open file for output at the end of a file. Output operations
always write data at the end of the file, expanding it. Repositioning
operations (fseek, fsetpos, rewind) are ignored. The file is created
if it does not exist.
What you should probably do is create an internal memory table that keeps all the unique entries and write it out to a new file after all processing is done. As you read the fd file, check the list and add a new entry if it is not already in the list. Then after you have finished processing fd, then and only then write out your list. Of course, this may be too big depending on the size of your data file.
You could append each unique entry to the output file as you go. but you would need to have some method of checking the previous entries without trying to read the output file.
The usual way to go about this is to read the input file word for word, store the necessary information in some way and then, after you have read all information from the file, write the desired output to the output file.
A rough skeleton of that approach might look like this:
int main()
{
const char *infile = "text.txt";
const char *outfile = "norep.txt";
FILE *in;
FILE *out;
char word[30];
// (1) Read all words
in = fopen(infile, "r"); // .. and enforce success
while (fscanf(in, "%29s", word) == 1) {
// store word somewhere
}
fclose(in);
// (2) Determine unique words somehow
// (3) Write out unique words
out = fopen(outfile, "w"); // .. and enforce success
for (i = 0; i < nunique; i++) {
fprintf(out, "%s\n", unique[i]);
}
fclose(out);
return 0;
}
The actual algorithm to fin the unique words is missing from this incomplete skeleton code.
If you really want to test the words in a file for uniqueness without using additional memory beyond the current word, you can open the input file twice, with independent file pointers. Then you can write a loop like so:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
const char *infile = "text.txt";
const char *outfile = "norep.txt";
FILE *in1;
FILE *in2;
FILE *out;
char word1[30];
char word2[30];
in1 = fopen(infile, "r");
in2 = fopen(infile, "r");
out = fopen(outfile, "w");
if (in1 == NULL || in2 == NULL || out == NULL) {
fprintf(stderr, "Could not open all required files.\n");
exit(1);
}
while (fscanf(in1, "%29s", word1) == 1) {
int count = 0;
while (fscanf(in2, "%29s", word2) == 1) {
if (strcmp(word1, word2) == 0) count++;
if (count > 1) break;
}
if (count == 1) fprintf(out, "%s\n", word1);
rewind(in2);
}
fclose(in1);
fclose(in2);
fclose(out);
return 0;
}
This will, of course, re-read the file as often as there are words in the file. Not a good approach to find the unique words in Moby-Dick. I recommend that you look into the memory-based approach.
I have known about this library from Heng Li for a while, but I have not attempted to use it until now, mostly because up until now python was fast enough for me.
Here is the link to the header: http://lh3lh3.users.sourceforge.net/kseq.shtml
When I attempt to use the following to parse a fasta file, it returns -1 for the length for the sequence line. I have looked over the Li's code and this seems to be designed mainly for FASTQ parsing, but he does say on his webpage that it also supports the FASTA format.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include "kseq.h"
// STEP 1: declare the type of file handler and the read() function
KSEQ_INIT(FILE*, read)
int main(int argc, char** argv) {
FILE* fp = fopen(argv[1], "r"); // STEP 2: open the file handler
kseq_t *seq = kseq_init(fp); // STEP 3: initialize seq
int l;
while ((l = kseq_read(seq)) >= 0) { // STEP 4: read sequence
printf("name: %s\n", seq->name.s);
if (seq->comment.l) printf("comment: %s\n", seq->comment.s);
printf("seq: %s\n", seq->seq.s);
if (seq->qual.l) printf("qual: %s\n", seq->qual.s);
}
printf("return value: %d\n", l);
kseq_destroy(seq); // STEP 5: destroy seq
fclose(fp);
return (0);
}
The FASTA I have been using to test with is the Hg19 GRCH37 ChrY.fa file available from multiple sources including the Broad Institute.
Any help would be appreciated.
First you should check the return value of fopen():
FILE* fp = fopen(argv[1], "r"); // STEP 2: open the file handler
if(fp == 0) {
perror("fopen");
exit(1);
}
Second, I looked at the header file and I think kseg_init takes an fd not a FILE *.
You can get an fd from a FILE * with fileno().
kseq_t *seq = kseq_init(fp); // STEP 3: initialize seq
Should be:
kseq_t *seq = kseq_init(fileno(fp)); // STEP 3: initialize seq
Here is the complete code that is working for me
#include <zlib.h>
#include <stdio.h>
#include "kseq.h"
KSEQ_INIT(int, read)
int main(int argc, char **argv)
{
FILE* fp;
kseq_t *seq;
int n = 0, slen = 0, qlen = 0;
fp = fopen(argv[1], "r");
seq = kseq_init(fileno(fp));
while (kseq_read(seq) >= 0)
++n ;//slen += seq->seq.l, qlen += seq->qual.l;
printf("%d\t%d\t%d\n", n, slen, qlen);
kseq_destroy(seq);
fclose(fp);
return 0;
}