Firstly, i'm not very familiarized with C, i come from Java, C#, C++... and possibly i inherited defects from this languages in order to realize this practice, well i have the follows question, here is my code:
#include <stdio.h>
#include <stdlib.h>
void decrypt(unsigned long* v, unsigned long* k);
const int MAX = 32;
const long delta = 0x9e3779b9;
long sum=0xC6EF3720;
int main() {
FILE *fp;
FILE *destino;
unsigned long v[2];
unsigned long k[4] = { 128, 129, 130, 131 };
unsigned long tam=0;
char* buffer;
char* aux[sizeof(unsigned long)];
int i;
if ((fp = fopen("image.png", "rb")) == NULL) {
printf ("Error! \n ");
return 0;
}
else {
fread(&aux,sizeof(unsigned long),1,fp);
memcpy(&tam,&aux,sizeof(unsigned long));
buffer = (char*)malloc(tam);
//fread(&buffer,1,tam,fp);
char *buffer2[28568];
fread(&buffer2,1,28568,fp);
/*for(i = 0;i < tam;++i) {
printf("%c", ((char *)buffer2)[i]);
}*/
for(i=4;i<tam;i+=8) {
memcpy(&v,&buffer2[i],8);
decrypt(&v,&k);
}
if ((result= fopen("image2.png", "rb")) == NULL) {
printf ("Error! \n ");
return 0;
}
else {
fwrite(v,sizeof(unsigned long)*2,1,result);
fclose (result);
fclose(fp);
}
}
return 0;
}
void decrypt(unsigned long* v, unsigned long* k) {
int i=0;
while(i<MAX) {
v[1] = v[1] -((4 << v[0])+(k[2]^v[0])+(sum^(5 >> v[0]))+k[3]);
v[0] = v[0] -((4 << v[1])+(k[0]^v[1])+(sum^(5 >> v[1]))+k[1]);
sum = sum-delta;
i++;
}
}
Where tam is the size of my binary file (image in this case) where i store first 4 bytes (unsigned long) where is located the size in my png file (28568)
When i create my char* buffer i have to assign dynamically with malloc but when i make a new fread from my file i get a "No source available for "msvrct!memcpy() at 0xrandom_memory_address" from Eclipse when i debug, well, i comment this line and i try to make it manually set a new buffer2 with 28568 as size of my array, apparently works, making a iteration of buffer2 prints ascii characters values but when i call decrypt for make the decryption of my image, the final result is stored in v array which i have to copy in a new file, i tried to search how to make a empty image png in C but i didn't find anything, so i created a copy of my encrypt image calling it "image2.png" but i suppose this not the "clean solution" for that, because for the other hand is not working at all.
For more explanation about this exercise just say that the decrypt funcion work with blocks of 8 bytes (64 bits) that through a key (array k) make a series of operation where they store in v array itself, crossing through the loop 8 in 8 and retrieve the value of buffer in v in each one, after the loop execution we have the result in v and only left to copy in a new file where finally show up the image decrypt.
It's a very complex practice for all of one newbies in C, it's driving my crazy trying to figure out what i doing wrong.
I hope anyone can see what i'm not able to for now.
I think you are having problems with the declarations of the buffers. I think the correct should be:
FILE *fp;
FILE *destino;
unsigned long v[2];
unsigned long k[4] = { 128, 129, 130, 131 };
unsigned long tam=0;
char* buffer;
char aux[sizeof(unsigned long)]; // without the "*"
int i;
if ((fp = fopen("image.png", "rb")) == NULL) {
printf ("Error! \n ");
return 0;
}
else {
fread(aux,sizeof(unsigned long),1,fp);
memcpy(&tam,aux,sizeof(unsigned long));
buffer = (char*)malloc(tam);
//fread(buffer,1,tam,fp); // without the "&" in this case
char buffer2[28568]; // without the "*"
fread(buffer2,1,28568,fp); // or fread(buffer,1,tam,fp);
/*for(i = 0;i < tam;++i) {
printf("%c", buffer2[i]); // or buufer[i] if you change to use it again
}*/
for(i=4;i<tam;i+=8) {
memcpy(v,&buffer2[i],8);
decrypt(v,k);
}
...
I don't fully understand what you are trying to accomplish, but one problem is here:
char* aux[sizeof(unsigned long)];
// ... some code ...
fread(&aux,sizeof(unsigned long),1,fp);
Understand that char* aux[sizeof(unsigned long)]; means that you are declaring a double pointer, but fread() prototype states that the destination is a single pointer:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
so what you should be doing instead is:
char aux[sizeof(unsigned long)];
// ... some code ...
fread(aux,sizeof(unsigned long),1,fp);
Don't complicate things that are not complicated!
You also do this mistake in other parts of your code, you need to re-check everything, ok? Again:
char *buffer2[28568];
fread(&buffer2,1,28568,fp);
should be:
char buffer2[28568];
fread(buffer2, 1, 28568, fp);
// or: fread(buffer2, 1, sizeof(buffer2), fp);
There are some interesting tutorials on pointers and arrays, I suggest you read some.
Related
I am working on a project in C to implement CBC mode on top of a skeleton code for DES with OpenSSL. We are not allowed to use a function that does the CBC mode automatically, in the sense that we must implement it ourselves. I am getting output but I have result files and my output is not matching up completely with the intended results. I also am stuck on figuring out how to pad the file to ensure all the blocks are of equal size, which is probably one of the reasons why I'm not receiving the correct output. Any help would be appreciated. Here's my modification of the skeleton code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
#include <sys/time.h>
#include <unistd.h>
#define ENC 1
#define DEC 0
DES_key_schedule key;
int append(char*s, size_t size, char c) {
if(strlen(s) + 1 >= size) {
return 1;
}
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
return 0;
}
int getSize (char * s) {
char * t;
for (t = s; *t != '\0'; t++)
;
return t - s;
}
void strToHex(const_DES_cblock input, unsigned char *output) {
int arSize = 8;
unsigned int byte;
for(int i=0; i<arSize; i++) {
if(sscanf(input, "%2x", &byte) != 1) {
break;
}
output[i] = byte;
input += 2;
}
}
void doBitwiseXor(DES_LONG *xorValue, DES_LONG* data, const_DES_cblock roundOutput) {
DES_LONG temp[2];
memcpy(temp, roundOutput, 8*sizeof(unsigned char));
for(int i=0; i<2; i++) {
xorValue[i] = temp[i] ^ data[i];
}
}
void doCBCenc(DES_LONG *data, const_DES_cblock roundOutput, FILE *outFile) {
DES_LONG in[2];
doBitwiseXor(in, data, roundOutput);
DES_encrypt1(in,&key,ENC);
printf("ENCRYPTED\n");
printvalueOfDES_LONG(in);
printf("%s","\n");
fwrite(in, 8, 1, outFile);
memcpy(roundOutput, in, 2*sizeof(DES_LONG));
}
int main(int argc, char** argv)
{
const_DES_cblock cbc_key = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
const_DES_cblock IV = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
// Initialize the timing function
struct timeval start, end;
gettimeofday(&start, NULL);
int l;
if ((l = DES_set_key_checked(&cbc_key,&key)) != 0)
printf("\nkey error\n");
FILE *inpFile;
FILE *outFile;
inpFile = fopen("test.txt", "r");
outFile = fopen("test_results.txt", "wb");
if(inpFile && outFile) {
unsigned char ch;
// A char array that will hold all 8 ch values.
// each ch value is appended to this.
unsigned char eight_bits[8];
// counter for the loop that ensures that only 8 chars are done at a time.
int count = 0;
while(!feof(inpFile)) {
// read in a character
ch = fgetc(inpFile);
// print the character
printf("%c",ch);
// append the character to eight_bits
append(eight_bits,1,ch);
// increment the count so that we only go to 8.
count++;
const_DES_cblock roundOutput;
// When count gets to 8
if(count == 8) {
// for formatting
printf("%s","\n");
// Encrypt the eight characters and store them back in the char array.
//DES_encrypt1(eight_bits,&key,ENC);
doCBCenc(eight_bits, roundOutput, outFile);
// prints out the encrypted string
int k;
for(k = 0; k < getSize(eight_bits); k++){
printf("%c", eight_bits[k]);
}
// Sets count back to 0 so that we can do another 8 characters.
count = 0;
// so we just do the first 8. When everything works REMOVE THE BREAK.
//break;
}
}
} else {
printf("Error in opening file\n");
}
fclose(inpFile);
fclose(outFile);
// End the timing
gettimeofday(&end, NULL);
// Initialize seconds and micros to hold values for the time output
long seconds = (end.tv_sec - start.tv_sec);
long micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
// Output the time
printf("The elapsed time is %d seconds and %d microseconds\n", seconds, micros);
}
Your crypto is at least half correct, but you have a lot of actual or potential other errors.
As you identified, raw CBC mode can only encrypt data which is a multiple of the block size, for DES 64 bits or 8 bytes (on most modern computers and all where you could use OpenSSL). In some applications this is okay; for example if the data is (always) an MD5 or SHA-256 or SHA-512 hash, or a GUID, or an IPv6 (binary) address, then it is a block multiple. But most applications want to handle at least any length in bytes, so they need to use some scheme to pad on encrypt and unpad on decrypt the last block (all blocks before the last already have the correct size). Many different schemes have been developed for this, so you need to know which to use. I assume this is a school assignment (since no real customer would set such a stupid and wasteful combination of requirements) and this should either have been specified or clearly left as a choice. One padding scheme very common today (although not for single-DES, because that is broken, unsafe, obsolete, and not common) is the one defined by PKCS5 and generalized by PKCS7 and variously called PKCS5, PKCS7, or PKCS5/7 padding, so I used that as an example.
Other than that:
you try to test feof(inpFile) before doing fgetc(inpFile). This doesn't work in C. It results in your code treating the low 8 bits of EOF (255 aka 0xFF on practically all implementations) as a valid data character added to the characters that were actually in the file. The common idiom is to store the return of getchar/getc/fgetc in a signed int and compare to EOF, but that would have required more changes so I used an alternate.
you don't initialize eight_bits which is a local-scope automatic duration variable, so its contents are undefined and depending on the implementation are often garbage, which means trying to 'append' to it by using strlen() to look for the end won't work right and might even crash. Although on some implementations at least some times it might happen to contain zero bytes, and 'work'. In addition it is possible in C for a byte read from a file (and stored here) to be \0 which will also make this work wrong, although if this file contains text, as its name suggests, it probably doesn't contain any \0 bytes.
once you fill eight_bits you write 'off-the-end' into element [8] which doesn't exist. Technically this is Undefined Behavior and anything at all can happen, traditionally expressed on Usenet as nasal demons. Plus after main finishes the first block it doesn't change anything in eight_bits so all further calls to append find it full and discard the new character.
while you could fix the above points separately, a much simple solution is available: you are already using count to count the number of bytes in the current block, so just use it as the subscript.
roundOutput is also an uninitialized local/auto variable within the loop, which is then used as the previous block for the CBC step, possibly with garbage or wrong value(s). And you don't use the IV at all, as is needed. You should allocate this before the loop (so it retains its value through all iterations) and initialize it to the IV, and then for each block in the loop your doCBCenc can properly XOR it to the new block and then leave the encrypted new block to be used next time.
your code labelled 'prints out the encrypted string' prints plaintext not ciphertext -- which is binary and shouldn't be printed directly anyway -- and is not needed because your file-read loop already echoes each character read. But if you do want to print a (validly null-terminated) string it's easier to just use fputs(s) or [f]printf([f,]"%s",s) or even fwrite(s,1,strlen(s),f).
your doCBCenc has a reference to printvalueofDES_LONG which isn't defined anywhere, and which along with two surrounding printf is clearly not needed.
you should use a cast to convert the first argument to doCBCenc -- this isn't strictly required but is good style and a good compiler (like mine) complains if you don't
finally, when an error occurs you usually print a message but then continue running, which will never work right and may produce symptoms that disguise the problem and make it hard to fix.
The below code fixes the above except that last (which would have been more work for less benefit) plus I removed routines that are now superfluous, and the timing code which is just silly: Unix already has builtin tools to measure and display process time more easily and reliably than writing code. Code I 'removed' is under #if 0 for reference, and code I added under #else or #if 1 except for the cast. The logic for PKCS5/7 padding is under #if MAYBE so it can be either selected or not. Some consider it better style to use sizeof(DES_block) or define a macro instead of the magic 8's, but I didn't bother -- especially since it would have required changes that aren't really necessary.
// SO70209636
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
#include <sys/time.h>
#include <unistd.h>
#define ENC 1
#define DEC 0
DES_key_schedule key;
#if 0
int append(char*s, size_t size, char c) {
if(strlen(s) + 1 >= size) {
return 1;
}
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
return 0;
}
int getSize (char * s) {
char * t;
for (t = s; *t != '\0'; t++)
;
return t - s;
}
void strToHex(const_DES_cblock input, unsigned char *output) {
int arSize = 8;
unsigned int byte;
for(int i=0; i<arSize; i++) {
if(sscanf(input, "%2x", &byte) != 1) {
break;
}
output[i] = byte;
input += 2;
}
}
#endif
void doBitwiseXor(DES_LONG *xorValue, DES_LONG* data, const_DES_cblock roundOutput) {
DES_LONG temp[2];
memcpy(temp, roundOutput, 8*sizeof(unsigned char));
for(int i=0; i<2; i++) {
xorValue[i] = temp[i] ^ data[i];
}
}
void doCBCenc(DES_LONG *data, const_DES_cblock roundOutput, FILE *outFile) {
DES_LONG in[2];
doBitwiseXor(in, data, roundOutput);
DES_encrypt1(in,&key,ENC);
#if 0
printf("ENCRYPTED\n");
printvalueOfDES_LONG(in);
printf("%s","\n");
#endif
fwrite(in, 8, 1, outFile);
memcpy(roundOutput, in, 2*sizeof(DES_LONG));
}
int main(int argc, char** argv)
{
const_DES_cblock cbc_key = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
const_DES_cblock IV = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
#if 0
// Initialize the timing function
struct timeval start, end;
gettimeofday(&start, NULL);
#endif
int l;
if ((l = DES_set_key_checked(&cbc_key,&key)) != 0)
printf("\nkey error\n");
#if 1
DES_cblock roundOutput; // must be outside the loop
memcpy (roundOutput, IV, 8); // and initialized
#endif
FILE *inpFile;
FILE *outFile;
inpFile = fopen("test.txt", "r");
outFile = fopen("test.encrypt", "wb");
if(inpFile && outFile) {
unsigned char ch;
// A char array that will hold all 8 ch values.
// each ch value is appended to this.
unsigned char eight_bits[8];
// counter for the loop that ensures that only 8 chars are done at a time.
int count = 0;
#if 0
while(!feof(inpFile)) {
// read in a character
ch = fgetc(inpFile);
#else
while( ch = fgetc(inpFile), !feof(inpFile) ){
#endif
// print the character
printf("%c",ch);
#if 0
// append the character to eight_bits
append(eight_bits,1,ch);
// increment the count so that we only go to 8.
count++;
#else
eight_bits[count++] = ch;
#endif
#if 0
const_DES_cblock roundOutput;
#endif
// When count gets to 8
if(count == 8) {
// for formatting
printf("%s","\n");
// Encrypt the eight characters and store them back in the char array.
//DES_encrypt1(eight_bits,&key,ENC);
doCBCenc((DES_LONG*)eight_bits, roundOutput, outFile);
#if 0
// prints out the encrypted string
int k;
for(k = 0; k < getSize(eight_bits); k++){
printf("%c", eight_bits[k]);
}
#endif
// Sets count back to 0 so that we can do another 8 characters.
count = 0;
// so we just do the first 8. When everything works REMOVE THE BREAK.
//break;
}
}
#if MAYBE
memset (eight_bits+count, 8-count, 8-count); // PKCS5/7 padding
doCBCenc((DES_LONG*)eight_bits, roundOutput, outFile);
#endif
} else {
printf("Error in opening file\n");
}
fclose(inpFile);
fclose(outFile);
#if 0
// End the timing
gettimeofday(&end, NULL);
// Initialize seconds and micros to hold values for the time output
long seconds = (end.tv_sec - start.tv_sec);
long micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
// Output the time
printf("The elapsed time is %d seconds and %d microseconds\n", seconds, micros);
#endif
}
PS: personally I wouldn't put the fwrite in doCBCenc; I would only do the encryption and let the caller do whatever I/O is appropriate which might in some cases not be fwrite. But what you have is not wrong for the requirements you apparently have.
I'm new in the world of C programming language and I was trying to read an image as a binary file. Unfortunately, when I tried to read the file I got an incomplete sequence ("\377\330\377", <incomplete sequence \340>).
I've already tried to use fread reading only the size of a byte and now I'm trying to use sizeof(unsigned char), but I always get the same incomplete sequence. Here is a part of the code:
caratteri **createStruct(unsigned char c[], caratteri car[], caratteri *ptr[], long size) {
for (long i = 0; i < size; i++) {
ptr[i] = &car[i];
car[i].first = &c[i];
car[i].last = &c[(size - 1 + i) % size];
car[i].index=i;
}
return ptr;
}
int compare(const void *a, const void *b) {
caratteri *ca = *(caratteri **) a;
caratteri *cb = *(caratteri **) b;
unsigned char *c1;
unsigned char *c2;
c1 = ca->first;
c2 = cb->first;
while (*c1 - *c2 == 0) {
c1++;
c2++;
}
return (*c1 - *c2);
}
caratteri **bwt(long size, FILE *file) {
FILE *risultato;
unsigned char *c = malloc(sizeof(unsigned char) * size);
fread(c, sizeof(unsigned char), size, file);
caratteri *car = malloc(sizeof(caratteri) * size);
caratteri **pCaratteri = malloc(sizeof(caratteri *) * size);
pCaratteri = createStruct(c, car, pCaratteri, size);
qsort(pCaratteri, size, sizeof(pCaratteri), compare);
risultato=fopen("risultato","wb");
for(long i = 0; i < size; i++)
fputc(*pCaratteri[i]->last,risultato);
fclose(risultato);
return pCaratteri;
}
int main() {
FILE *file;
file = fopen("thumbnail.jpg","rb");
if (file == NULL) {
printf("Errore di apertura file!");
exit(2);
}
fseek(file, SEEK_SET, SEEK_END);
long size = ftell(file)+1;
rewind(file);
caratteri **car = bwt(size, file);
FILE *risultato;
decryptbwt(risultato);
return 0;
}
This is not the full code but I need this part to work properly.
Also, I need this code to work with every kind of file (.txt, .jpg, .png, etc) and I need the \0 character in case of a txt file, that's why I used ftell(file)+1 but I'm not sure this is appropriate. Anyway, how can I read a file in binary mode avoiding the problem of incomplete sequences?
Thank you for your answers and sorry for the dumb question but I'm new in this world.
I need to take an extra \0 because I'm using an algorithm that needs an end of string character, that's why I'm using ftell with a +1. This algorithm should work with every kind of file so I need to read it correctly and then use the burrows wheeler transform in order to sort the file that I need to compress. Also, I'm not sure that I have to use the fseek in that way but I think there is not another way to get the size of the file.
I'm having a difficult time trying to open a WAV file for reading. When I compile and run my code, I do not get any errors. I am adding the code that I am messing with (assuming necessary libraries have been called). The program is supposed to display the contents of the WAV file and although I enter a valid filename and extension, the statement "Invalid Filename. Try Again." is still being printed to the screen. The other method I attempted was enter the directory of the file instead of just the name, and when I do that, my program ends and nothing is displayed. Any guidance would be helpful and thank you in advance!
main(){
FILE *fin;
printf("\nEnter filename of WAV file: \n");
char filename[256];
scanf("%s",&filename);
fin = fopen(filename,"rb"); // opens in rb
if(!fin) // if file doesn't exist
{
printf("Invalid filename. Try again.\n");
}
else // if fin opens succesfully
{
printf("\nFile opened succesfully\n");
char *header;
header = (char *)malloc(44);
if(header == NULL)
{
printf("Error in allocating memory.");
return 0;
}
fread(header,1,44,fin);
char *chunkid;
unsigned int *chunksize;
char *format;
char *subchunk1id;
unsigned int *subchunk1size;
unsigned short int *audioformat;
unsigned short int *numchannels;
unsigned int *samplerate;
unsigned int *byterate;
unsigned short int *blockalign;
unsigned short int *bitspersample;
char *subchunk2id;
unsigned int *subchunk2size;
unsigned int *data;
chunkid = header;
chunksize = (unsigned int *)(header + 4);
format = header + 8;
subchunk1id = header + 12;
subchunk1size = (unsigned int *)(header + 16);
audioformat = (unsigned short int *)(header + 18);
numchannels = (unsigned short int*)(header + 20);
samplerate = (unsigned int*)(header + 24);
byterate = (unsigned int*)(header + 28);
blockalign = (unsigned short int*)(header + 30);
bitspersample = (unsigned short int*)(header + 32);
subchunk2id = header + 36;
subchunk2size = (unsigned int*)(header + 40);
data = (unsigned int*)(header + 44);
printf("\n%c%c%c%c",*(header),*(header+1),*(header+2),*(header+3));
printf("\n%d",*chunksize);
printf("\n%c%c%c%c",*(header + 8),*(header + 9), *(header + 10), *(header + 11));
printf("\n%c%c%c%c",*(header + 12),*(header + 13), *(header + 14), *(header + 15));
printf("\n%d",*subchunk1size);
printf("\n%d",*audioformat);
printf("\n%d",*numchannels);
printf("\n%d",*samplerate);
printf("\n%d",*byterate);
printf("\n%d",*blockalign);
printf("\n%d",*bitspersample);
printf("\n%c%c%c%c",*(header + 36),*(header + 37),*(header + 38), *(header + 39));
printf("\n%d",*subchunk2size);
printf("\n%d",*data);
fclose(fin);
} // end of else
} // end of main
Try using
if(!fin)
{
perror("Error:");
}
it will print the right error message for you to easily diagnose why your file couldn't be opened. May be your program cannot find the file specified by you or you might not have permissions to open it. Here's a list of errors you may encounter while opening a file.
The other possible problem that I could see is that you are using scanf to read from stdin into your char array. What if the path specified by you contains white-spaces? Every word followed by a White-space will be considered like a different string. And you'll get only the first longest possible word that doesn't contain white-space into it. So, your program isn't reading the entire path. You can try
scanf("%[^\n]", filename) which will read until a '\n' is encountered. Beware! This exposes you to buffer overflow possibilities, that if you pass a valid string set to the program which is of length greater than 256, you'll be writing beyond the boundaries of your char array and which isn't good. So try scanf("%255[^\n]", filename) or try using fgets() doc SO which provides buffer overflow protection.
Using warnings while compiling the code would have revealed your mistake.
Proposal for improvement, describe the header as a struct like:
typedef struct
{
char riff_tag[4];
int32_t riff_length;
char wave_tag[4];
char fmt_tag[4];
int32_t fmt_length;
int16_t audio_format;
int16_t num_channels;
int32_t sample_rate;
int32_t byte_rate;
int16_t block_align;
int16_t bits_per_sample;
char data_tag[4];
int32_t data_length;
}waveFileHeader, *waveFileHeaderptr ;
and read it like:
waveFileHeaderptr header =malloc ( sizeof (waveFileHeader));
fread (header , sizeof (waveFileHeader), 1 , fin);
will make the following code and handeling less messy
int getLineCount() {
int ret = 0;
char c;
while ((c = fgetc(stdin)) != EOF)
if (c == '\n')
ret++;
return ret + 1;
}
void fill(char *WORD) {
int charIndex = 0;
char c;
while ((c = fgetc(stdin)) != EOF) {
*(WORD + charIndex++) = c;
}
}
int main() {
int lineNum = getLineCount();
char *WORD = (char*)calloc(lineNum * 18,sizeof(int));
fill(WORD);
return 0;
}
Here is the part of my code, and my question is(as you can see):
I'm trying to read stdin's content twice, but after the getLineCount function, it stays at the EOF and I can't read it again in fill function.
Im taking stdin from the user with this command in Linux;
$./output < text_file.txt
Is there any way to roll back stdin to starting character? If not, how can I fix this problem?
Thanks.
You can use rewind(stdin) to set the stream back to the start of file, but be aware that it is not guaranteed to work, especially if the stream is a pipe, a terminal or a device.
Your allocation scheme is incorrect: you could compute the size of the file and then allocate that many bytes, but your current (char*)calloc(lineNum * 18,sizeof(int)); allocates 18 times the size of type int for each line. Some files with short lines will fit in this array while others will invoke undefined behavior.
Note that c must be defined as int for c = fgetc(stdin); to properly store all values including the EOF special value.
Don't use rewind.
You can, of course, save the data you read from stdin (potentially in a file if it's too large for main memory) and operate on that.
Another possibility is this:
struct callback {
void (*call) (char, void *);
void * data;
};
void with_characters_from(FILE * file, struct callback const * callbacks, size_t count) {
int c;
while ((c = fgetc(file)) != EOF) {
char character = c & 0xFF;
for (size_t i = 0; i < count; ++i) {
callbacks[i].call(character, callbacks[i].data);
}
}
}
You inverse control, such that no longer your functions are "pulling data out of" stdin, but rather the data (characters) are "pushed to" them. Note that this can lead to callback hell, and in C you sacrifice a good portion of type safety (as well as code clarity .. no first class functions / closures ... sigh).
A small test:
struct counter_data {
char const character;
unsigned count;
};
void counter (char character, void * vptr) {
struct counter_data * data = vptr;
if (character == data->character) {
++(data->count);
}
}
int main() {
struct counter_data data [2] = {
{'a', 0}, {'x', 0}};
struct callback callbacks [2] = {
{&counter, &(data [0])},
{&counter, &(data [1])}};
with_characters_from (stdin, callbacks, 2);
printf("Counted %c %u times \n", data [0].character, data [0].count);
printf("Counted %c %u times \n", data [1].character, data [1].count);
return 0;
}
As already noted, for your particular example, you should consider a completely different approach: If possible compute the required size beforehand. If you exceed that size (which you should always test for), then use realloc in order to get a larger chunk of memory.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
The input file is in.wav. I have to read chunks (succeeded) and to read samples to normalize the audio file...
The problem is that it crashes while trying to fing the max and min values of .wav file's samples.
It will just find the minimum value and the maximum one in the array, but it crashes...
Tell me what is wrong, please.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#define hdr_SIZE 64
typedef struct FMT
{
char SubChunk1ID[4];
int SubChunk1Size;
short int AudioFormat;
short int NumChannels;
int SampleRate;
int ByteRate;
short int BlockAlign;
short int BitsPerSample;
} fmt;
typedef struct DATA
{
char Subchunk2ID[4];
int Subchunk2Size;
int Data[441000];
} data;
typedef struct HEADER
{
char ChunkID[4];
int ChunkSize;
char Format[4];
fmt S1;
data S2;
} header;
int main()
{
FILE *input = fopen( "in.wav", "rb"); /// nameIn
if(input == NULL)
{
printf("Unable to open wave file (input)\n");
exit(EXIT_FAILURE);
}
FILE *output = fopen( "out.wav", "wb"); /// nameOut
header hdr;
fread(&hdr, sizeof(char), hdr_SIZE, input);
/* NOTE: Chunks has been copied successfully. */
/*###############################*/
/*##### UPDATE (char *ptr;) #####*/
/*###############################*/
char *ptr; // 'int' was written here instead of 'char'. That's was a stupid mistake...
long n = hdr.S2.Subchunk2Size;
/// COPYING SAMPLES...
ptr = malloc(sizeof(hdr.S2.Subchunk2Size));
while ( n-- != 0 )
{
fread(&ptr, 1, 1, input); // Continues reading after the least 'stop' place.
} // I was being told here (on "stack") that it is so...
n = hdr.S2.Subchunk2Size; // Resetting 'n'.
int min = ptr[0], max = ptr[0], i;
/* THE PROBLEM IS HERE: */
for ( i = 0; i < n; i++ )
{
if ( ptr[i] < min ) // If the next elements is less than previous, swap them.
min = ptr[i];
if ( ptr[i] > max ) // If the next elements is bigger than previous, swap them.
max = ptr[i];
}
printf("> > >%d__%d\n", min, max); // Displaying of 'min' and 'max'.
fclose(input);
fclose(output);
return 0;
}
UPDATE:
EUREKA! This is all because of 8-bits per sample! I must manipulate with them ( with samples ) as with a type of char. (see my "### UPDATE ###"-comment in the code)
This code:
/// COPYING SAMPLES...
ptr = malloc(sizeof(hdr.S2.Subchunk2Size));
while ( n-- != 0 )
{
fread(&ptr, 1, 1, input); // Continues reading after the least 'stop' place.
} // I was being told here (on "stack") that it is so...
Overwrites the first byte of the ptr variable n times. This corrupts ptr's value. Even if you fixed it to read into the allocated buffer instead (by removing the &), you would only be rewriting the first byte of the allocated memory.
What you probably intended was:
fread(ptr, 1, n, input);
Notice the while loop is not needed. But, that would be a guess on my part regarding your true intentions.
You are corrupting your malloc()ed ptr with:
fread(&ptr, 1, 1, input); /* overwrite the content of ptr */
and so the program crash if it tries to use ptr.
Use:
fread(ptr, 1, 1, input);
Or better: no while loop, and use:
fread(ptr, 1, n, inout);
As pointed by others, ptr is not incremented in this block,
while ( n-- != 0 )
{
fread(&ptr, 1, 1, input); // FIXME, ptr not incremented
}
But you are are trying to store 1 byte data as integer; is this what you intend ??