I'm trying to reproduce a .raw image file using a small program I've written in C, but every time I run the program my output file becomes unreadable.
All my program does is take every pixel and write it to a corresponding output file.
Also note, this program is written to support only grayscale images.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin, *fout;
char path_in[64], path_out[64], *rev, px;
int width, height, read, row, i;
printf("Input file name: ");
scanf("%s", path_in);
printf("Output file name: ");
scanf("%s", path_out);
printf("Width of image (in pixels): ");
scanf("%d", &width);
printf("Height of image (in pixels): ");
scanf("%d", &height);
fin = fopen(path_in, "r");
fout = fopen(path_out, "w");
row = 0;
rev = (char *)malloc(width * sizeof(char));
while(row < height)
{
for(i = 0; i < width; i++)
{
read = fread(&px, sizeof(char), 1, fin);
rev[i] = (unsigned int)px;
}
for(i = 0; i < width; i++)
if(i < width && row < height)
fwrite(&rev[i], sizeof(char), 1, fout);
row++;
}
fclose(fout);
fclose(fin);
return 0;
}
There might be some other problems with it, but you've told fopen to open the files in text mode:
fin = fopen(path_in, "r");
fout = fopen(path_out, "w");
instead of binary mode:
fin = fopen(path_in, "rb");
fout = fopen(path_out, "wb");
which is what's appropriate for image data.
You're also doing odd casting that might be munging your data:
char ..., *rev, px;
...
rev = (char *)malloc(width * sizeof(char));
...
rev[i] = (unsigned int)px;
The (unsigned int) cast is unnecessary at best.
Related
I was hoping to get a bit of help, I am implementing an inversion counter algorithm to take in 50,000 intergers and display the inversions and time it took to run the algorithm, I am having a hard time allocating and saving the integers from the file into an array. My code complies and runs but nothing happens
here is what I have:
int main(int argc, char** argv)
{
int n, i;
int inversions=0;
int *A;
FILE *file;
char filename[100];
clock_t start, end;
double totalTime;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if(file == NULL)
{
printf("Error opening file!\n");
return 0;
}
fscanf(file, "%d", &n);
A = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
fscanf(file, "%d", &A[i]);
}
start = clock();
inversions = countInversionsBruteForce(A, n);
end = clock();
totalTime = (double) (end - start) / CLOCKS_PER_SEC;
printf("Brute Force Algorithm\n");
printf("Number of inversions: %d\n", inversions);
printf("Execution time: %f\n", totalTime);
I think I have noth allocated array size and saved it properly
Your program is incomplete so I was not able to compile it. Minimized the problem to just loading the data into your array:
Formatted code for readability.
Generated a suitable input file. Most likely this is your problem but you have not shared your input sample with us.
Added missing include files.
Remove argc, argv as you not using them.
Minimize scope of variables. Use size_t instead of int for unsigned values.
Max string size on obtaining file name
Check return value for scanf(), fopen(), fscanf().
Printing out the data read to demonstrate it's working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Enter filename: ");
char filename[100];
if(scanf("%99s", filename) != 1) {
printf("scanf failed\n");
return 1;
}
FILE *file = fopen(filename, "r");
if(!file) {
printf("Error opening file!\n");
return 1;
}
size_t n;
fscanf(file, "%zu", &n);
if(!n) {
printf("n must be positive");
return 1;
}
int *A = malloc(n * sizeof(*A));
for(size_t i = 0; i < n; i++)
if(fscanf(file, "%d", &A[i]) != 1) {
printf("fscanf() failed\n");
return 1;
}
printf("n = %zu\n", n);
printf("A = ");
for(size_t i = 0; i < n; i++)
printf("%d%s", A[i], i + 1 < n ? ", " : "\n");
}
with 1.txt as:
4
1
2
3
4
a sample session looks like this:
Enter filename: 1.txt
n = 4
A = 1, 2, 3, 4
I am struggling with reading floats from a file which I created during the program lifetime. I was trying to rewind the file, I was trying to open and close file before reading it, I was trying to put values directly in the table and by another variable. Idk what can I do more, what's wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
float *tab;
float x = 0.0;
int i, size;
FILE *fp;
fp = fopen("data.txt", "w+");
if (fp == NULL) {
printf("Error");
system("PAUSE");
exit(1);
}
printf("Size of table: ");
scanf("%d", &size);
tab = (int*)malloc(size * sizeof(int));
for (i = 0; i < size; i++) {
tab[i] = (8.0 - 2.0) * (float)rand() / RAND_MAX + 2.0;
fprintf(fp, "%.2f ", tab[i]);
}
for (i = 0; i < size; i++) {
printf("%.2f ", tab[i]);
}
printf("\n");
fp = fclose;
fp = fopen("data.txt", "w+");
tab = realloc(tab, 2*size);
for (i = 0; i < size * 2; i+=2) {
fscanf(fp, "%f", &x);
printf("%.2f ", x);
//tab[i + 1] = tab[i] / 2;
}
/*for (i = 0; i < size * 2; i++) {
printf("%.2f \n", tab[i]);
}*/
fp = fclose;
printf("\n");
system("PAUSE");
return 0;
}
There are a number of problems in this code. First, as noted in the comments, the initial allocation is wrong. You are allocating space for floats, not ints. You could have avoided this problem entirely if you had written the call to malloc() like this:
tab = malloc(sizeof(*tab) * size);
Here, the result of malloc() is not cast, since it is not necessary in C. Also, note that instead of using an explicit type for the argument to the sizeof operator, the identifier is used instead. This guarantees that whatever the type of tab, which must be a pointer, the result of sizeof will be correct. Also, you should always check to see if an allocation was successful.
fp = fclose is just wrong. This should be fclose(fp). After this, when you open the file again with "w+", the file is truncated to zero length, and you lose the data that was previously written. Since the file has already been opened with "w+", just use rewind(fp) here.
For the reallocation that you do, aside from that the arguments are not quite right here, there is a potential problem that you should be aware of. realloc() can return a null pointer in the event of an allocation error. If this happens, and you are directly assigning the result of realloc() to the pointer for which you are reallocating (tab), then you will lose the reference to previously allocated memory. This is a memory leak, and lost data. The way to do this is to store the result of realloc() in a temporary pointer, which you test. If the temporary pointer is a null pointer, there was an error; otherwise you can safely assign the return value to the original pointer.
And as already noted, when you call fclose() the final time, it needs to be fclose(fp).
Here is a modified code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
float *tab, *temp; // added temp for realloc() check
float x = 0.0;
int i, size;
FILE *fp;
fp = fopen("data.txt", "w+");
if (fp == NULL) {
printf("Error");
system("PAUSE");
exit(1);
}
printf("Size of table: ");
scanf("%d", &size);
/* You should always check for allocation errors */
if ((tab = malloc(sizeof(*tab) * size)) == NULL) {
fprintf(stderr, "Error in initial allocation\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < size; i++) {
tab[i] = (8.0 - 2.0) * (float)rand() / RAND_MAX + 2.0;
fprintf(fp, "%.2f ", tab[i]);
}
for (i = 0; i < size; i++) {
printf("%.2f ", tab[i]);
}
printf("\n");
// fclose(fp); // not fp = fclose;
// fp = fopen("data.txt", "w+"); // when you reopen, the file is truncated
rewind(fp); // but just do this
/* Fixed this reallocation */
temp = realloc(tab, sizeof(*tab) * size * 2);
if (temp == NULL) {
fprintf(stderr, "Error in reallocation\n");
exit(EXIT_FAILURE);
}
tab = temp;
for (i = 0; i < size * 2; i+=2) {
fscanf(fp, "%f", &x);
printf("%.2f ", x);
//tab[i + 1] = tab[i] / 2;
}
/*for (i = 0; i < size * 2; i++) {
printf("%.2f \n", tab[i]);
}*/
fclose(fp); // not fp = fclose;
printf("\n");
system("PAUSE");
return 0;
}
Sample interaction:
Size of table: 10
2.65 5.67 5.21 3.22 3.07 4.29 5.96 5.96 5.15 7.36
2.65 5.67 5.21 3.22 3.07 4.29 5.96 5.96 5.15 7.36
I am writing a simple C program to read float values from a tab file using fscanf.
Here is the tab file:
> 7 <--------------this declares the number of pairs of values
> 4.0 5.0
> 5.5 4.0
> 1.0 5.0
> 5.0 2.5
> 2.0 2.0
> 4.0 2.0
> 1.0 1.5
Here is my program:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
char filename[100];
FILE *fp;
int n=0;
int N;
double x[22];
double y[22];
int main(void) {
printf("Input filename: ");
fgets(filename, 100, stdin); //read filename
//check if enter sign exist in filename
N = (int)strlen(filename);
for (int i = 0; i < N; i++) {
if (filename[i] == '\n') {
filename[i] = '\0';
}
}
//printf("%s", filename);
fp = fopen(filename, "r"); //open file
if (fp == NULL) //check file
{
printf("\nCannot open input file %s\n", filename);
exit(1);
}
fscanf(fp, "%d", &n); //read Data
for (int i = 0; i < n; i++) {
fscanf(fp,"%f%f", &x[i], &y[i]);
}
fclose(fp); //close file
//check data retrieved
for (int i = 0;i < n;i++) {
printf("%f//%f//\n", x[i], y[i]);
}
The result is 14 values of 0.0000 rather than values in the tab file.
Working on a project where I have to have a file that is generated numbers. First line is a generated int. Followed by a floats (separate lines). (I'm doing it separate lines because I feel it makes more sense as I have to read it two different ways for the bin packing problems which I need this for... Like one way of reading one at a time and another storing it in an array.. But want to get this down first)
Getting a seg fault when I try to read my file for a float after reading an int. Edit: Error occurs in readOffline.
int randomFunction()
{
FILE *fp;
int i;
fp = fopen("theItems.txt", "w" );
if (fp == NULL)
printf("Error: file can't be opened.\n");
srand(time(NULL) );
int random_number = rand();
printf("Random Number %d\n", random_number);
fprintf(fp,"%d",random_number);
fclose(fp);
fp = fopen("theItems.txt", "a");
int numberOfItems = rand();
printf("NumberOfItems: %d\n",numberOfItems);
for(i = 0; i < 10; i++)
{
fp = fopen("theItems.txt", "a");
float number = (float)rand()/(float)(RAND_MAX);
fprintf(fp,"%f",number);
fprintf(fp,"%s", "\n");
fclose(fp);
}
return numberOfItems;
}
void readOffline( int numberOfItems)
{
FILE *fp;
int n = 0,i;
float nu = 0.00;
fp = fopen("theItems.txt", "r");
if (fp == NULL)
printf("Error: file can't be opened.\n");
fseek(fp,SEEK_SET,0);
fscanf(fp,"%d",&n);
printf("Number read: %d\n", n);
float array[numberOfItems];
// for(i = 0; i < 3; i++)
// {
fscanf(fp,"%f",&nu);
// array[i] = nu;
// }
fclose(fp);
printf("Int:%d\n", n);
int j;
// for(j = 0; j < 3; j++)
// printf("Float Number:%f\n", array[j]);
}
int main()
{
int numberOfItems = randomFunction();
readOffline(numberOfItems);
return 0;
}
Just trying to get an understanding why it causes a seg error when I // it out I can get it to read my int but sometimes it isn't the right int read. But yeah.
Please let me know if I need any more details or need to be more clear anywhere
You have multiple issues in your code:
You open the output file multiple times in randomFunction(), you even leak a stream handle and leave it open.
You do not exit the function when fopen() returns NULL. The rest of the code invokes undefined behavior if fp == NULL.
The same problem is present in readOffline(): if fp == NULL, you should return from the function immediately.
you do not output a linefeed after the first random number in the output file.
you always output 10 random numbers.
most importantly: the random number returned by the randomFunction() is potentially huge, allocating an array with local storage larger than a few megabytes is likely to cause undefined behavior. Try and reduce the maximum random number of values.
Here is a proposed correction:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randomFunction(void) {
FILE *fp;
int i;
fp = fopen("theItems.txt", "w");
if (fp == NULL) {
printf("Error: file can't be opened.\n");
return -1;
}
srand(time(NULL));
int random_number = rand();
printf("Random Number %d\n", random_number);
fprintf(fp, "%d\n", random_number);
int numberOfItems = 1 + rand() % 100; /* between 1 and 100 */
printf("NumberOfItems: %d\n", numberOfItems);
for (i = 0; i < numberOfItems; i++) {
float number = rand() / (float)(RAND_MAX);
fprintf(fp, "%f\n", number);
}
fclose(fp);
return numberOfItems;
}
void readOffline(int numberOfItems) {
FILE *fp;
int n = 0, i;
fp = fopen("theItems.txt", "r");
if (fp == NULL) {
printf("Error: file can't be opened.\n");
return;
}
fscanf(fp, "%d", &n);
printf("Number read: %d\n", n);
float array[numberOfItems];
for (i = 0; i < numberOfItems; i++) {
if (fscanf(fp, "%f", &array[i]) != 1)
break;
}
fclose(fp);
printf("Int:%d\n", n);
for (int j = 0; j < i; j++) {
printf("Float Number %d: %f\n", j, array[j]);
}
}
int main(void) {
int numberOfItems = randomFunction();
readOffline(numberOfItems);
return 0;
}
Note that I kept your semantics: the random number at the start of the file is not the number of floating point values that follow. I suspect it should be?
I would say that depending on the particular compiler that you are using, then this could be a problem in setting up the actual array. This is (as an example) discussed in Variable Sized Arrays vs calloc in C From the discussions, you should use calloc and free. Another point is that you need to make sure that your value is greater than 3 and not too big. Since the array is only in the local scope of readOffline(), you should not connect it to the variable numberOfItems.
float array[3];
for(i = 0; i < 3; i++)
{
fscanf(fp,"%f",&nu);
array[i] = nu;
}
I'm trying to write a C program that takes a .raw grayscale image and reverses it, pixel by pixel.
I store each pixel in a 1D char array, and then write each pixel to an output file, just in opposite order.
My program works if I try to reproduce the image, but if I try modifying the indices of my array, I produce an unreadable file.
Reproduce Original
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin, *fout;
char ipath[64], opath[64], *rev, px;
int i, row, read, width, height;
printf("Name of input file: ");
scanf("%s", ipath);
printf("Name of output file: ");
scanf("%s", opath);
printf("Width of image: ");
scanf("%d", &width);
printf("Height of image: ");
scanf("%d", &height);
fin = fopen(ipath, "rb");
fout = fopen(opath, "wb");
rev = (char *)malloc(width * sizeof(char));
row = 0;
while(row < height)
{
for(i = 0; i < width; i++)
{
read = fread(&px, sizeof(char), 1, fin);
rev[i] = px;
}
for(i = 0; i < width; i++)
if(i < width && row < height)
fwrite(&rev[i], sizeof(char), 1, fout);
row++;
}
fclose(fout);
fclose(fin);
return 0;
}
Reverse Image
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin, *fout;
char ipath[64], opath[64], *rev, px;
int i, row, read, width, height;
printf("Name of input file: ");
scanf("%s", ipath);
printf("Name of output file: ");
scanf("%s", opath);
printf("Width of image: ");
scanf("%d", &width);
printf("Height of image: ");
scanf("%d", &height);
fin = fopen(ipath, "rb");
fout = fopen(opath, "wb");
rev = (char *)malloc(width * sizeof(char));
row = 0;
while(row < height)
{
for(i = 0; i < width; i++)
{
read = fread(&px, sizeof(char), 1, fin);
rev[width - 1 - i] = px;
}
for(i = 0; i < width; i++)
if(i < width && row < height)
fwrite(&rev[i], sizeof(char), 1, fout);
row++;
}
fclose(fout);
fclose(fin);
return 0;
}
For testing purposes, I've just used scanf() though I'm aware of its issues.