Reading a File in C isn't working? - c

so I tried looking around and I couldn't find an answer. I'm trying to read from a file I write in a different program. Writing it works fine, but when I try and read it, there is no output at all. Here's the code.
struct data{
int tp, gpm, deg;
};
int main()
{
struct data list[21];
int p[21];
list[0].tp = 10;
FILE * fout;
fopen("data_list", "r");
for(int i = 0; i < 21; i++){
fscanf(fopen, "%d:\t%d\t%d\t%d\n", &p[i], &list[i].tp, &list[i].gpm, &list[i].deg);
}
for(int i = 0; i < 21; i++){
printf("%d:\t%d\t%d\t%d\n", p[i], list[i].tp, list[i].gpm, list[i].deg);
}
fclose(fout);
return 0;
}
Here's the file I'm trying to read
-10:651 17 108
-9: 514 16 142
-8: 588 16 169
-7: 542 10 160
-6: 531 17 127
-5: 688 15 158
-4: 619 18 122
-3: 658 14 170
-2: 588 11 182
-1: 541 12 139
+0: 641 19 114
+1: 668 17 200
+2: 517 19 157
+3: 589 13 121
+4: 696 13 140
+5: 526 12 157
+6: 630 12 137
+7: 685 11 105
+8: 556 11 120
+9: 645 15 188
+10:624 19 185
Can anyone help me out? I've only been learning C for a couple months, most of it selftaught

fscanf(fopen, "%d:\t%d\t%d\t%d\n"
I have no idea how that possibly even compiled, but you are passing a function pointer where a FILE* is required. That definitely will not work correctly.
The correct thing to pass there is the return value from your fopen() call (which at the moment you've been discarding).

Related

Why does my c code not add the correct null zero at the end like it is supposed to and keeps printing out code?

I do not know why my code does not seem to be working properly. I am reading from a file, and grabbing each line and from there I am using my own function to try and break down each of the lines and add them to character arrays in a structure and then add those structures to an array. But for whatever reason, when I am trying to indivudually print out the individual values for all of the information it keeps printing out all of it. From what I am seeing, for whatever reason even though my function strsub is supposed to add a '\0' at the end, it does not seem to be doing that. So every time I pass in the pointer to the begging of each of the character variables it does not stop until the end of the whole structure so it starts by printing out the whole string and then prints out less and less. Is that the problem that I really have or am I missing something else?
This is my code so far. I first just tried creating a struct and filling the array with each pass, but unfortunantly I had the same issue.
#define _CRT_SECURE_NO_WARNINGS // Since I want to strictly use ANSI C and not Microsoft C without getting the warning message, I'm adding this line of code before I include header files.
#include <stdio.h> // "#include" includes the contents of another file, commonly called header file, into the source code file.
#include <string.h>
#define MAX 100
FILE *fp, *csit;
void strsub(char buf[], char sub[], int start, int end);
void printArray(struct trainCartrain[]);
struct trainCar {
char car[10];
char type[2];
char weight[6];
char length[3];
char horsepower[3];
char numberInTrain[4];
};
int main() {
struct trainCar ar[7];
struct trainCar train;
// test and open input file and output file.;
if (!(fp = fopen("train.txt", "r"))) {
printf("train.txt could not be opened for input.");
exit(1);
}
if (!(csit = fopen("csit.txt", "w"))) {
printf("csit.txt could not be opened for output.");
exit(1);
}
int i = 0;
char buf[MAX];
while (!feof(fp)) {
fgets(buf, MAX, fp);
strsub(buf, train.car, 0, 9);
strsub(buf, train.type, 10, 11);
strsub(buf, train.weight, 12, 17);
strsub(buf, train.length, 18, 20);
strsub(buf, train.horsepower, 21, 23);
strsub(buf, train.numberInTrain, 24, 27);
printf("%s", train.car);
printf("%s", train.type);
ar[i] = train;
i++;
}
printArray(ar);
fclose(csit);
fclose(fp);
return 0;
}
void strsub(char buf[], char sub[], int start, int end) { //strsub () grabs a substring, sub, from a string, buf, given the start and end index within the string.
int i, j;
for (j = 0, i = start; i <= end; i++, j++) {
sub[j] = buf[i];
}
sub[j] = '\0';
//end with the null terminator character that signifies the end of a string.
}
My file is small and simple, textfile
Boxcar D 44000 55 16 45
Hopper B 23000 62 18 33
Tanker G 15000 45 30 12
Autocar A 30000 37 23 6
Livestock L 56500 50 18 19
Coalcar C 49300 53 22 100
Flatcar F 18000 66 15 25
and what it prints out is
Boxcar D 44000 55 16 45
D 44000 55 16 45
44000 55 16 45
55 16 45
16 45
45
Hopper B 23000 62 18 33
B 23000 62 18 33
23000 62 18 33
62 18 33
18 33
33
Tanker G 15000 45 30 12
G 15000 45 30 12
15000 45 30 12
45 30 12
30 12
12
Autocar A 30000 37 23 6
A 30000 37 23 6
30000 37 23 6
37 23 6
23 6
6
Livestock L 56500 50 18 19
L 56500 50 18 19
56500 50 18 19
50 18 19
18 19
19
Coalcar C 49300 53 22 100
Flatcar F 18000 66 15 25C 49300 53 22 100
Flatcar F 18000 66 15 2549300 53 22 100
Flatcar F 18000 66 15 2553 22 100
Flatcar F 18000 66 15 2522 100
Flatcar F 18000 66 15 25100
Flatcar F 18000 66 15 25Flatcar F 18000 66 15 25F 18000 66 15 2518000 66 15 2566 15 2515 2525
can someone please explain what I am doing wrong? I do have to use this function strsub for my class too.
I am just trying to get it to print out the individual charachter data and not the whole string each time. I think it is an issue with the terminating zero at the end and when I tried debugging it does not seem to be adding that for some reason. I don't know why though, if that is the problem.
strsub(buf, train.car, 0, 9); accesses train.car with index 0 till 9 in the loop and then index 10 outside, but that's already out of bounds for a char car[10];.
Solution:
Increase the size of all of your arrays by 1 to have space for the 0-terminator of the string.
Also have a look at Why is “while( !feof(file) )” always wrong? . It is not related to your problem, but you might run into that problem in the next minutes.
Instead of
while (!feof(fp)) {
fgets(buf, MAX, fp);
....
}
use
while (fgets(buf, MAX, fp)) {
....
}
You missed a space in void printArray(struct trainCartrain[]);. It should be void printArray(struct trainCar train[]); and moved to after the definition of struct trainCar.
You also have to #include <stdlib.h> to use exit(1);

Erreur de segmentation (core dumped) when trying to read txt file in C

I want to read a pgm file in C language using fgets but i get an error and i don't know which instruction cause it.
Here is my code :
FILE* file = NULL;
char chaine[TAILLE_MAX] = "";
int elts[TAILLE_MAX];
image = fopen("test.txt", "r+");
if(image != NULL)
{
int i=0;
while (fgets(chaine, TAILLE_MAX, file) != NULL)
{
elts[i] = atoi(chaine);
printf("%d\n", i);
i++;
}
}
It reads until the last line of the file. Here is the output :
...
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
RUN FINISHED; Segmentation fault; core dumped; real time: 140ms; user: 0ms; system: 0ms
The probleme is not the file but i think it's about the fgets function
The text-based PGM files will contain many values on each line for the pixels. With pixels[i] = atoi(chaine) you only convert the first of those numbers.
You need to parse or tokenize the lines to get all the pixels.
And of course, you need to make sure that the values you read can fit in the destination integer array, which needs to be W * H elements large (where W is the image width and H is the image height).
And as with all image formats, even text-based such, I really recommend you find a library to handle it for you.

Algorithms used in ImageMagick

I used Imagemagick in my project. I implemented a sub-image detection system using the compare command of ImageMagick. It is working well giving fine results. By reading articles i got to know that ImageMagick compares pixels of small image at every possible position within the pixels of larger image.And also i got to know ImageMagick detects rotated images and scaled images using Fuzzy factor.I was able to find the source code related to compare command.
const Image *reconstruct_image,double *distortion,ExceptionInfo *exception)
585 {
586 CacheView
587 *image_view,
588 *reconstruct_view;
589
590 double
591 area;
592
593 MagickBooleanType
594 status;
595
596 register ssize_t
597 j;
598
599 size_t
600 columns,
601 rows;
602
603 ssize_t
604 y;
605
606 status=MagickTrue;
607 rows=MagickMax(image->rows,reconstruct_image->rows);
608 columns=MagickMax(image->columns,reconstruct_image->columns);
609 area=0.0;
610 image_view=AcquireVirtualCacheView(image,exception);
611 reconstruct_view=AcquireVirtualCacheView(reconstruct_image,exception);
612 #if defined(MAGICKCORE_OPENMP_SUPPORT)
613 #pragma omp parallel for schedule(static,4) shared(status) \
614 magick_threads(image,image,rows,1) reduction(+:area)
615 #endif
616 for (y=0; y < (ssize_t) rows; y++)
617 {
618 double
619 channel_distortion[MaxPixelChannels+1];
620
621 register const Quantum
622 *magick_restrict p,
623 *magick_restrict q;
624
625 register ssize_t
626 x;
627
628 if (status == MagickFalse)
629 continue;
630 p=GetCacheViewVirtualPixels(image_view,0,y,columns,1,exception);
631 q=GetCacheViewVirtualPixels(reconstruct_view,0,y,columns,1,exception);
632 if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL))
633 {
634 status=MagickFalse;
635 continue;
636 }
637 (void) ResetMagickMemory(channel_distortion,0,sizeof(channel_distortion));
638 for (x=0; x < (ssize_t) columns; x++)
639 {
640 double
641 Da,
642 Sa;
643
644 register ssize_t
645 i;
646
647 if ((GetPixelReadMask(image,p) == 0) ||
648 (GetPixelReadMask(reconstruct_image,q) == 0))
649 {
650 p+=GetPixelChannels(image);
651 q+=GetPixelChannels(reconstruct_image);
652 continue;
653 }
654 Sa=QuantumScale*GetPixelAlpha(image,p);
655 Da=QuantumScale*GetPixelAlpha(reconstruct_image,q);
656 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
657 {
658 double
659 distance;
660
661 PixelChannel channel=GetPixelChannelChannel(image,i);
662 PixelTrait traits=GetPixelChannelTraits(image,channel);
663 PixelTrait reconstruct_traits=GetPixelChannelTraits(reconstruct_image,
664 channel);
665 if ((traits == UndefinedPixelTrait) ||
666 (reconstruct_traits == UndefinedPixelTrait) ||
667 ((reconstruct_traits & UpdatePixelTrait) == 0))
668 continue;
669 distance=QuantumScale*fabs(Sa*p[i]-Da*GetPixelChannel(reconstruct_image,
670 channel,q));
671 channel_distortion[i]+=distance;
672 channel_distortion[CompositePixelChannel]+=distance;
673 }
674 area++;
675 p+=GetPixelChannels(image);
676 q+=GetPixelChannels(reconstruct_image);
677 }
678 #if defined(MAGICKCORE_OPENMP_SUPPORT)
679 #pragma omp critical (MagickCore_GetMeanAbsoluteError)
680 #endif
681 for (j=0; j <= MaxPixelChannels; j++)
682 distortion[j]+=channel_distortion[j];
683 }
684 reconstruct_view=DestroyCacheView(reconstruct_view);
685 image_view=DestroyCacheView(image_view);
686 area=PerceptibleReciprocal(area);
687 for (j=0; j <= MaxPixelChannels; j++)
688 distortion[j]*=area;
689 distortion[CompositePixelChannel]/=(double) GetImageChannels(image);
690 return(status);
691 }
Anyone have an idea about what are the conditions they are searching for in the following code snippet?
if ((traits == UndefinedPixelTrait) ||
666 (reconstruct_traits == UndefinedPixelTrait) ||
667 ((reconstruct_traits & UpdatePixelTrait) == 0))
In case you're wondering how these values are used:
http://www.learncpp.com/cpp-tutorial/3-8a-bit-flags-and-bit-masks/
Those values are nothing but different bits. They are different so you can combine them and check them in a disambiguous way.
In case you don't know the meaning of UndefinedPixelTraits and so on, just google the word and you'll end up in the ImageMagick documentation:
https://www.imagemagick.org/include/porting.php
Pixel Traits
Each pixel channel includes one or more of these traits:
Undefined no traits associated with this pixel channel Copy do not
update this pixel channel, just copy it Update update this pixel
channel Blend blend this pixel channel with the alpha mask if it's
enabled We provide these methods to set and get pixel traits:
GetPixelAlphaTraits() SetPixelAlphaTraits() GetPixelBlackTraits()
SetPixelBlackTraits() GetPixelBlueTraits() SetPixelBlueTraits()
GetPixelCbTraits() SetPixelCbTraits() GetPixelChannelTraits()
SetPixelChannelTraits() GetPixelCrTraits() SetPixelCrTraits()
GetPixelGrayTraits() SetPixelGrayTraits() GetPixelGreenTraits()
SetPixelGreenTraits() GetPixelIndexTraits() SetPixelIndexTraits()
GetPixelMagentaTraits() SetPixelMagentaTraits() GetPixelRedTraits()
SetPixelRedTraits() GetPixelYellowTraits() SetPixelYellowTraits()
GetPixelYTraits() SetPixelYTraits() For convenience you can set
the active trait for a set of pixel channels with a channel mask and
this method:
SetImageChannelMask() Previously MagickCore methods had channel
analogs, for example, NegateImage() and NegateImageChannels(). The
channel analog methods are no longer necessary because the pixel
channel traits specify whether to act on a particular pixel channel or
whether to blend with the alpha mask. For example, instead of
NegateImageChannel(image,channel); we use:
channel_mask=SetImageChannelMask(image,channel);
NegateImage(image,exception); (void)
SetImageChannelMask(image,channel_mask);
If you want to know how and why each method is handling those flags read the respective documentation or the code itself.

Write a C program that reads in the integers from the accompanying data file and use insertion sort to store the sorted data into an array

Write a C program that implements a simple array-based insertion sort.
Your program must read in the integers from the accompanying data file
and use insertion sort to store the sorted data into an array. If you
must insert an element between two existing values, then you must also
move (or shift) the elements all elements with an index >= the index
where you wish to insert the new element. Note that you can find the
insertion sort algorithm in the textbook and the slides.
This is the ints from the text file. The ints are under each other and not the way they are shown here:
879
646
80
385
741
57
370
240
111
400
262
678
951
506
720
508
792
863
677
864
70
5
591
440
989
478
867
636
278
827
692
243
806
676
158
550
425
226
783
129
876
714
125
721
164
555
730
146
596
947
174
837
48
589
808
868
694
677
379
62
580
165
956
139
215
14
45
552
98
154
702
661
997
825
363
782
229
915
281
397
295
219
231
476
253
22
873
504
653
698
772
184
453
508
977
863
624
947
104
926
This the code I have for now. I am getting the addresses in order but now the integers from the file. When i comment out the insertionSort function, the numbers print fine but obviously not in order. What am i doing wrong?
#include <stdio.h>
#include<stdio.h>
void insertionSort(int *, int);
int main()
{
int i,num,array[1000];
FILE *fp = fopen("data_a5.txt","r");
fscanf(fp,"%d",&num);
if(fp== NULL)
{
printf("Error reading File!\n");
return;
}
while(!feof(fp))
{
fscanf(fp,"%d", &array[num]);
//printf("%d\n", array[num]);
}
insertionSort(array,num);
for(i=0;i<num;i++)
printf("%d\n",&array[i]);
fclose(fp);
return 0;
}
void insertionSort(int *value, int size)
{
int i,j,temp;
for(i = 0; i <= size; i++)
{
for(j = i; j >= 0; j--)
{
if(value[j+1]<value[j])
{
temp=value[j+1];
value[j+1]=value[j];
value[j]=temp;
}
else
break;
}
}
}
If your task is to have your array sorted as items are inserted (ie. "live") you best bet is to use linked structures.
For example:
struct myinst
{
int mynum;
struct myinst *prev;
struct myinst *next;
};
There a lot of examples, here is one: http://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htm
When you insert a new item to have your array/linked list sorted you go through your linked list and find the item that is nearest to the new one and then perform an insert by creating new memory an change prev/next addresses in existing items so that they point to the new item.

sscanf not detecting the right numbers

I'm having a hard time using sscanf to scan hour and minutes from a list. Below is a small snip of the list.
1704 86 2:30p 5:50p Daily
1711 17 10:40a 2:15p 5
1712 86 3:10p 6:30p 1
1731 48 6:25a 9:30a 156
1732 100 10:15a 1:30p Daily
1733 6 2:15p 3:39p Daily
I've tried this, but it keeps getting me segmentation Fault.(I'm putting this information into structures).
for(i=0;i<check_enter;i++){
sscanf(all_flights[i],
"%d %d %d:%d%c %d:%d%c %s",
&all_flights_divid[i].flight_number,
&all_flights_divid[i].route_id,
&all_flights_divid[i].departure_time_hour,
&all_flights_divid[i].departure_time_minute,
&all_flights_divid[i].departure_time_format,
&all_flights_divid[i].arrival_time_minute,
&all_flights_divid[i].arrival_time_minute,
&all_flights_divid[i].arrival_time_format,
&all_flights_divid[i].frequency);
printf("%d ",all_flights_divid[i].flight_number);
printf("%d ",all_flights_divid[i].route_id);
printf("%d ",all_flights_divid[i].departure_time_hour);
printf("%d ",all_flights_divid[i].departure_time_minute);
printf("%c ",all_flights_divid[i].departure_time_format);
printf("%d ",all_flights_divid[i].arrival_time_hour);
printf("%d ",all_flights_divid[i].arrival_time_minute);
printf("%c ",all_flights_divid[i].arrival_time_format);
printf("%s\n",all_flights_divid[i].frequency);
}
This is how I declared it.
struct all_flights{
int flight_number;
int route_id;
int departure_time_hour;
int departure_time_minute;
char departure_time_format;
int arrival_time_hour;
int arrival_time_minute;
char arrival_time_format;
char frequency[10];
};
struct all_flights all_flights_divid[3000];
These are the results I get
1704 86 2 30 p 0 50 p Daily
1711 17 10 40 a 0 15 p 5
1712 86 3 10 p 0 30 p 1
1731 48 6 25 a 0 30 a 156
1732 100 10 15 a 0 30 p Daily
1733 6 2 15 p 0 39 p Daily
Small mistake, that might be the problem:
this:
&all_flights_divid[1].flight_number,
should be:
&all_flights_divid[i].flight_number,
// ^
Edit:
Also, you read arrival_time_minute twice, and not reading arrival_time_hour at all. Fix it and it should be OK.
Most of the results seem to be fine, except the first field.
Now if you check your code..
&all_flights_divid[1]
fix it with
&all_flights_divid[i]

Resources