(C) Program doesn't print all values from input file - c

Working with C.
OK so this is probably something obvious but for some reason my program will only print a certain number of values from a .dat input file as opposed to printing all of them. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N = 0;
int j;
float i;
const char Project_Data[] = "FloatValues.dat";
FILE *input = fopen(Project_Data, "r");
if(input != (FILE*) NULL)
{
while(fscanf(input, "%e", &i) == 1)
{
printf("%e\n",i);
++N;
}
printf("\t The number of values in this file is: %d\n", N);
fclose(input);
}
else
printf("Input file could not be read.\n");
return(0);
}
Yeah, so there's about 100000 values or so to be printed yet I only seem to be able to get 20000. The values in the file are ordered sequentially and the compiler only seems to start printing nearer the bottom of the file, after about 80000 or so values.
Anybody know where I'm going wrong?

Related

How to print a substring in C

simple C question here!
So I am trying to parse through a string lets say: 1234567W
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
}
}
return 0;
My output so far shows: "123d" because of the "%.4sd" in the printf function.
I now need to get the next two numbers, "45". Is there a regex expression I can use that will allow me to get the next two digits of a string?
I am new to C, so I was thinking more like "%(ignore the first 4 characters)(print next 2 digits)(ignore the last two digits)"
input: pic
output: pic
Please let me know.
Thanks all.
printf("Next two: %.2s\n", p + 4); should work.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
printf("Next two: %.2s\n", p + 4);
}
}
return 0;
}
Side note: I added a missing stdio.h include. Please turn on compiler warnings, since this error would've been caught by them.

How to read in pixel values from .pgm file and copy it into an array. c-programming

I've been stuck on this for a while. How would I go about copying pixel values 0-255 from a pgm file into an array? This is what I have so far. I know I'm off from what it is suppose to be.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, int *argv[])
{
int i = 0, j = 0;
unsigned int str[1000];
FILE *pgmFile;
if (argc != 2)
{
printf ("ERROR, Not enough arguments.");
exit(EXIT_FAILURE);
}
if ((pgmFile = fopen(argv[1], "r")) == NULL)
{
printf ("ERROR, File cannot be opened");
exit(EXIT_FAILURE);
}
do
{
fscanf (pgmFile, "%d", str[i]);
printf ("%d", str[i]);
i++;
}
while (str[i] != EOF);
fclose (pgmFile);
return 0;
}
You should first read in the header (3 lines).
Using the data from the header, you can setup a for loop reading in the Y amount of lines. Within each line you should read X amount of pixel data and a new-line. If any of read functions returns an error-code, you should print out an error message and abort.
https://en.wikipedia.org/wiki/Netpbm_format

Print out first line of input file char by char, but nothing comes to screen

So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}

How to read and store 2 float values seperated by a comma from a file into two arrays where each float is stored in one array

my text file format is this:
3.2 , 5.6
444.2 , 555
112.34 , 32.3
i want to read the above information present within file name file.txt and store it in two arrays a,b where a will have the float value before the comma and b will have the float value after the comma
Use fgets() in a loop to read each line. Then once you have the line, use sscanf() to scan out the two floating-point numbers, like so:
while(fgets(line, sizeof line, myfile) != NULL)
{
if(sscanf(line, "%f,%f", &a[i], &b[i]) == 2)
{
++i;
}
else
printf("Parse error in %s", line);
}
Note that the return value from sscanf() says how many conversions that succeeded. If it isn't two, we don't want to move forward in the array. Remember to make sure i is initialized to 0 before the loop, of course.
E.g.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DATA_SIZE 10
int main (void){
char filename[256] = "file.txt";
char input_line[128];
FILE *fp;
float a[DATA_SIZE], b[DATA_SIZE];
int i,j;
if(NULL==(fp=fopen(filename, "r"))){
perror("input file open");
return -1;
}
i=0;
while(NULL!=fgets(input_line, sizeof(input_line), fp)){
if(*input_line == '\n') continue;
a[i]=atof(strtok(input_line, " ,\n"));//ok even this ","
b[i]=atof(strtok(NULL , " ,\n"));
++i;
}
//check print
for(j=0;j<i;++j){
printf("a[%d]=%g, b[%d]=%g\n", j, a[j], j, b[j]);
}
return 0;
}

Program not accepting all values from file

I posted a problem yesterday regarding a certain segment of my code. The aim was to basically scan in data values from a .dat file into an array, print the values whilst also counting how many values were in the file.
Sounds pretty simple, but my program only seemed to print a certain number of the values. More specifically, of a data file containing over 300000 values, it would only print the last 20000 and nothing else.
So I left it, finished the rest of my code and now it's the last part I have to sort. I've made a few changes and tried actually printing an output .dat file now so I can see what I'm getting. The code is below by the way.
Initally I assumed perhaps it was something related to the memory allocation of my array (was getting a segmentation error? when putting the whole code together) so I created an external function that counted the number of values instead (that works).
My only problem now is that it still only chooses to print 20000 values and then the rest are 0s. I was thinking perhaps it had something to do with the type but they all contain 7 dps in scientific notation. Here's a sample of some of the values:
8.4730000e+01 1.0024256e+01
8.4740000e+01 8.2065599e+00
8.4750000e+01 8.3354644e+00
8.4760000e+01 8.3379525e+00
8.4770000e+01 9.8741315e+00
8.4780000e+01 9.0966478e+00
8.4790000e+01 9.4760274e+00
8.4800000e+01 7.1199807e+00
8.4810000e+01 7.1990172e+00
Anyone see where I'm going wrong? I'm sorry for the long question, it's just been bugging me for the last day or so and no matter what I change nothing seems to help. Any kind of input would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int count(int);
const char df[]="data_file.dat";
const char of[]="output_file.dat";
int main(int argc, char *argv[])
{
FILE *input, *output;
int i, N;
float *array;
N = count(i);
input = fopen(df, "r");
output = fopen(of, "w");
array = (float*)malloc(N*sizeof(float));
if((input != (FILE*) NULL) && (output != (FILE*) NULL))
{
for(i = 0; i < N; i++)
{
fscanf(input, "%e", &array[i]);
fprintf(output, "%d %e\n", i, array[i]);
}
fclose(input);
fclose(output);
}
else
printf("Input file could not be opened\n");
return(0);
}
int count(int i)
{
FILE *input;
input = fopen(df, "r");
int N = 0;
while (1)
{
i = fgetc(input);
if (i == EOF)
break;
++N;
}
fclose(input);
return(N);
}
Your biggest problem is that count() doesn't count float values; it counts how many characters are in the file. Then you try to loop and call fscanf() more times than there are values in the file. The first times, fscanf() finds a float value and scans it; but once the loop reaches the end of file, fscanf() will be returning an EOF status. It seems possible that fscanf() will set the float value to 0.0 when it returns EOF.
I suggest you rewrite so that you don't try to pre-count the float values. Write a loop that just repeatedly calls fscanf() until it returns an EOF result, then break out of the loop and close the files.
P.S. If you are going to write a function like count(), you should pass in the filename as an argument instead of hard-coding it. And your version of count() takes an integer argument but just ignores the value; instead, just declare a temp variable inside of count().
EDIT: Okay, here is a complete working program to solve this problem.
#include <stdio.h>
int
main(int argc, char **argv)
{
FILE *in_file, *out_file;
unsigned int i;
if (argc != 3)
{
fprintf(stderr, "Usage: this_program_name <input_file> <output_file>\n");
return 1; // error exit with status 1
}
in_file = fopen(argv[1], "r");
if (!in_file)
{
fprintf(stderr, "unable to open input file '%s'\n", argv[1]);
return 1; // error exit with status 1
}
out_file = fopen(argv[2], "w");
if (!out_file)
{
fprintf(stderr, "unable to open output file '%s'\n", argv[2]);
return 1; // error exit with status 1
}
for (i = 0; ; ++i)
{
int result;
float x;
result = fscanf(in_file, "%e", &x);
if (1 != result)
break;
fprintf(out_file, "%d %e\n", i, x);
}
return 0; // successful exit
}
Note that this version doesn't need to allocate a large array; it just needs a single temporary float variable. Maybe your program will need to store all the float values. In that case, write a count() function that uses a loop similar to the above loop, using fscanf() to count float values.
Also note that this program checks for errors after calling fopen() and fscanf().
You are allocating far more floats in memory (N) than you need because your N is the number of characters in the file, not the number of values in it.
Also, how did you determine that there are 300000 values in the file?

Resources