I recently done a program and ended up getting wrong on my homework. I had all the right steps however, I was not supposed to do it from the command line but run it from the IDE (if that makes sense).
What I am supposed to do is go into the file "numbers.txt" and read the integers in it (there are numbers already in there). I am suppose to find the sum, product and the highest integer and output those to a text called "stat.txt". However, I am confused on how to do it from my compiler. I have both files in the same directory however when I run it in the compiler, it says "Can not read input file." and I have no idea how to use the compiler to just read the text files because I am so use to using the command line.
Here's my code (I could not get max to fit in with the code).
int main (int argc, char *argv[]) {
int number = 0;
int sum = 0;
int product = 1;
int max = 0;
FILE *input, *output;
input = fopen("numbers.txt", "r");
output = fopen("stat.txt", "w");
if (input == NULL) {
printf("Can not read the input file\n");
exit(-1);
}
while ((fscanf(input, "%d", &number)) != EOF) {
sum = sum + number;
product = product * number;
if (number > max){
max = number;
}
}
fprintf(output, "Sum : %d\n", sum);
fprintf(output,"Product : %d\n", product);
fprintf(output, "Largest: %d", max);
fclose(input); fclose(output);
}
What IDE are you using? You are supplying fopen with a relative path to numbers.txt, it must exist in the same directory as the executable.
Either place numbers.txt into the same folder where your IDE builds the program, or supply it with an absolute path like '/home/username/Desktop/number.txt'
Related
The C program I am trying to write is meant to take a file of integer values and sum the first number with the second, then the first with the third, the first with the forth, and so on. Then sum the second with the third, the second with the forth, and so on. It is also meant to print a message whenever a predetermined value is met while adding all the numbers (in my case, it's 10), and print out the time it took for this program to execute.
However, when the program starts going through the list of integers in the file I am taking values from (over 10,000 integers are in this file), it seems that it gets to the 124th loop and then gives me a Segmentation Fault (Core Dumped) error. When I reduce the number of integers to be added to under 124, the program works fine.
Why am I getting this Segmentation Fault error? Is it in the way that I set up my While loops? Is there any way I can remedy this?
#include<stdio.h>
#include <time.h>
int main(){
FILE *fptr1,*fptr2,*temp;
fptr1 = fopen("input.txt", "r") ;
int num1,num2;
int sum=0;
int c=0;
if (fptr1 == NULL) {
printf("File not open\n");
return 0;;
}
int count=0;
clock_t t;
t = clock();
// the problem seems to be in this while loop//
while(fscanf(fptr1, "%d", &num1) !=EOF){
count++;
fptr2 = fopen("input.txt", "r") ;
int count1=0;
while(fscanf(fptr2, "%d", &num2) !=EOF){
count1++;
if(count1>count){
sum=num1+num2;
if(sum==10){c++;}
}
}
}
printf("sum of 10 was found in %d iterations of loop",c);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("Time taken :%lf", time_taken);
fclose(fptr1);
fclose(fptr2);
return 0;
}
When the file has over 124 integers, it gives me this:
the output when over 124 integers
and when he file has less than 124 integers, it gives me this:
the output when under 124 integers
The problem seems to be opening way too many file handles, but the fix should be simple:
while(fscanf(fptr1, "%d", &num1) !=EOF){
count++;
// This fopen() call might fail, you should check the result
fptr2 = fopen("input.txt", "r");
int count1 = 0;
while(fscanf(fptr2, "%d", &num2) != EOF) {
// ...
}
// If you open a file, you must close it before re-opening
fclose(fptr2);
}
This is quite wasteful, though, there's no reason to open over and over, instead
just rewind the file and use it again:
fptr2 = fopen("input.txt", "r");
while(fscanf(fptr1, "%d", &num1) !=EOF) {
// Move back to the beginning of the file before reading
rewind(fptr2);
count++;
int count1 = 0;
while(fscanf(fptr2, "%d", &num2) != EOF) {
// ...
}
}
fclose(fptr2);
Another thing to note here is your variable names are extremely opaque. fptr2 doesn't communicate anything about what this is supposed to be used for, or what that file might contain. If it correlates with an input source, consider input or finput or even fin. Likewise, count1 and count and an even more mysterious c are confusing. Counting what? For what reason?
I have a C code that opens and reads a text file with numbers then computes the area of a rectangle using those numbers.
My Code is:
#include <stdio.h>
int main()
{
FILE *ifile;
float length, width;
float maxarea = 0, maxlen, maxwidth;
ifile = fopen("rectangles.txt", "r");
while (feof(ifile) <= 0)
{
fscanf(ifile, "%f %f", &length, &width);
if (length * width > maxarea)
{
maxarea = length * width;
maxlen = length;
maxwidth = width;
}
}
printf("Maximum area is %f for rectangle with length %f and width %f",
maxarea, maxlen, maxwidth);
fclose(ifile);
return(0);
}
When I debug it this shows up:
When I retry it it shows this error:
With the same code when I run it on a Linux Terminal it works and gives the right output. (recLarge is the executable file)
How can I get the same output on Visual Studio 2017?
Edit your project settings and add any command-line options to Command Arguments:
Pay attention to the Working Directory setting.
Obviously, your main function is not currently set up for this. You need to add support for arguments:
int main(int argc, char **argv)
{
if (argc <= 1)
{
fprintf(stderr, "Not enough arguments\n");
return EXIT_FAILURE;
}
char *filename = argv[1];
FILE *ifile = fopen(filename,"r");
if (!file)
{
perror("Cannot open file");
return EXIT_FAILURE;
}
// ...
return EXIT_SUCCESS;
}
I needed to create the text file "rectangles.txt" under resources as a text file. The main C code will be under source. The dubugging for the code needs to have rectangles.txt as the command argument. Compile as should be Compile as C code(/TC).
I'm trying to read two records form a file, where one is hexadecimal formated number. Well I'm newcomer to C, before when I been reading hexadecimal, generated by ftok(), I just used printf("%x", key) and it worked fine. Now when I try to read it from the file, it does not work that way.
So my code looks like this:
int countRecords(FILE *f_p) {
int tmp_key = 0;
int tmp_msgqid = 0;
int n = 0;
while (!feof(f_p)) {
if (fscanf(f_p, "%x %i", &tmp_key, &tmp_msgqid) != 2)
break;
n = n + 1;
}
return n;
}
Later on i read this value in the code like:
printf("Records: %i \n", countRecords(f_msgList));
And this compiles with no warnings. Anyway when I run the program the value of countRecords(f_msgList) is 0, when the file have a bunch of data in it:
5a0203ff 360448
850203ff 393217
110203ff 425986
EDIT:
Here is the code where the file is opened or created:
FILE *f_msgList;
f_msgList = fopen("../message_queues.list", "a");
// if file does not exist then create one and check for errors
if (f_msgList == NULL) {
FILE *f_tmp;
f_tmp = fopen("../message_queues.list", "w");
if (f_msgList == NULL) {
fprintf(stderr, "Error occurred while creating the file! \n");
exit(1);
} else
f_msgList = f_tmp;
}
Problems
You opened the file in "append" mode. which does not let you read through the file.
If you want to write and then read the file, file pointer must be reset to the starting of the file.
feof(f_p) is worst way of checking whether file pointer is at end of the file.
Solution
Open File in "read" mode by 'r' or in append+read mode 'a+'.
if you are writing in to the file. reset it using rewind(f_p); after writing.
check out this way to read through the file :
int ret, ans, key;
while ((ret = fscanf(fp, "%x %i", &key, &ans))) {
if (ret == EOF)
break;
else
printf("%x %i \n",key, ans);
}
here integer ret is :
EOF, if the pointer is reached end of file.
0, if no input matched with the variable
(greater than 0), that is, number of matched variables with the file input
I'm a student learning C for the first time. I typed in an example the professor gave the class, which is supposed to read in some integers from a file called "input.txt".
Here's the code:
#include <stdio.h>
int main() {
FILE *ifp;
int num = -1, sum = 0;
ifp = fopen("input.txt", "r");
while (num!= 0) {
fscanf(ifp, "%d", &num);
sum +=num;
}
fclose(ifp);
printf("The sum is %d.\n", sum);
return 0;
}
I'm trying to get this program to print out the "sum" like it should, but when I run it, there are no errors yet the only output I get is (11db).
I created a file called "input.txt" and saved it to the desktop, but it's not working.
The file "input.txt" contains:
1
2
3
4
5
I don't know if I'm supposed to somehow, somewhere, define the file path or where/how to do this.
Any help is much appreciated.
Thanks!
My guess would be that the error is because opening the file fails. You should check that fopen returns non-NULL. Opening a file is an operation that often fails. For example:
ifp = fopen("input.txt", "r");
if (ifp == NULL) {
fprintf(stderr, "Couldn't open the file for reading.\n");
}
Unless given a full path name starting with a "/", fopen opens files in the current working directory of the process, and that is probably not the desktop.
Also, when you reach the end of the file, fscanf will return the value EOF. The variable num will not be set to zero. This is a way to read a file of integers:
while (fscanf(ifp, "%d", &num) == 1) {
sum += num;
}
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?