I have recently learnt about using I/O files in C, and one of my book exercises asks me to read lines of pairs of number and add them, then print them to an output file.
What I mean is:
If the input file looks like:
12 13
24 26
23 13
the output file will be:
25
50
36
I have tried reading it as a string using:
fscanf(in, "%s", &string); //in is the input file pointer
but it doesn't work (causes a seg. fault)
My problem is that I am unable to take in the lines of pairs of numbers using the fscanf function, as I do not know how many lines there are in the input file.
Thus, my question is: How do I read an input file containing an amount of lines if I do not know how many lines there are? Can I read it as a string?
Thank you in advanced.
Michael
Here's some working code:
#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
FILE *fp = fopen("filename.txt", "r"); //open file for reading
FILE *f = fopen("file.txt", "w"); //open file for writing
while (!feof (fp)) //reading file until end of file
{
fscanf (fp, "%d", &a);
fscanf (fp, "%d", &b);
int sum = a + b;
fprintf(f, "%d\n", sum); //writing summation to a file
}
fclose(f); //close files
fclose(fp);
return 0;
}
Just create filename.txt and write numbers in it. And create blank file.txt.
Related
I am trying to find an easier way of reading a text file. I have never programed in C before so this is all new to me. My goal is to be able to run my program and have it automatically print to the screen. What I have below works but I have to enter the file in every time. Any help would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter name of a file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
return 0;
}
This is the output:
Enter name of a file you wish to see
warning: this program uses gets(), which is unsafe.
Data.txt
The contents of Data.txt file are:
1
2
3
4
5
6
7
8
9
10
Will you always be reading from Data.txt ? If so you can hardcode the file name and replace gets(file_name); with char * file_name = "Data.txt" . If you do this also remove the current definition of file_name to avoid a redefinition error.
There are a few ways to define the filename without user intervention. In all cases, remove
printf("Enter name of a file you wish to see\n");
gets(file_name);
Replace gets(file_name); with strcpy(file_name, "Data.txt");.
You will need to also #include <string.h>.
Replace file_name[25] with file_name[] = "Data.txt"
Replace char ch, file_name[25]; with char ch; char *file_name = "Data.txt";
You could also declare the string as constant: const char *file_name = "Data.txt";.
Replace gets(file_name); with snprintf(file_name, (sizeof(file_name)/sizeof(file_name[0]))-1, "Data.txt");
sizeof(file_name)/sizeof(file_name[0]) calculates the maximum length of the array by dividing the total array's size by the length of a single element. We subtract 1 to reserve an element for the string termination character '\0'.
snprintf() would allow you to build the filename programmatically.
Remove , file_name[25].
Replace fp = fopen(file_name, "r"); with fp = fopen("Data.txt", "r");.
Replace printf("The contents of %s file are:\n", file_name); with printf("The contents of the file are:\n");
(Note the loss of functionality)
so I'm working on this program that read from a text file which is filled with non prime and prime numbers, so it first reads all the numbers from one text file and then it outputs only the prime numbers to another text file.
Let say one text file has:
233
179
178
199
198
157
On the second it should print or copy:
233
179
199
157
So far I have worked on the following code:
#include <stdio.h>
int main()
{
FILE *in_file;
int numbers;
in_file = fopen("file1.txt", "r");
while ( fscanf(in_file, "%d", &numbers) == 1) {
printf("%d\n", numbers);
}
fclose(in_file);
}
return 0;
}
The problem with the above code is that the reads are wrong, the output to the screen is not the same as in file1, and I'm not sure whether is to do with the getw() function or somewhere else in the code?
The int getw(FILE *) function is for reading an integer directly from the bytes of a file, not for reading an integer from the textual contents of a file.
If you wish to read integers from a file, one by one, use fscanf instead:
FILE *in_file = fopen("file1.txt", "r");
FILE *out_file = fopen("file2.txt", "w");
int num;
while (fscanf(in_file, "%d", &num) == 1) {
if (is_prime(num)) {
fprintf(out_file, "%d\n", num);
}
}
fclose(in_file);
fclose(out_file);
I would like to copy a huge txt file and 'shrink' it. this is my code, but it seems it's still takes a lot of time reading the file. is there a way to read from a specific line number to EOF? for instance, the first 1 million lines are not useful to me, how to read from line 1 million. or anyway to read from EOF?
include<stdio.h>
include<stdlib.h>
void main() {
FILE *fp1, *fp2;
char ch;
int i = 1;
int n = 0;
int k;
fp1 = fopen("co.data", "r"); /* open a file to read*/
fp2 = fopen("Output.txt", "w"); /* open a file to write*/
printf("please enter how many lines do not need to be copied\n");
scanf ("%d", &k);
while (1) {
ch = fgetc(fp1); /* a loop to read/copy the file*/
if (ch == '\n') /* record the number of lines*/
i++;
if (ch == EOF)
break;
else if (i>k)
putc(ch, fp2);
}
printf("File copied Successfully!\n");
printf("number of lines read is %d\n",i-1);
printf("number of lines copied is %d\n",i-1-k);
fclose(fp1);
fclose(fp2);
}
There are two potential answers to your question, depending on if your file has known line lengths or not.
is there a way to read from a specific line number to EOF
In a file with line lengths are completely arbitrary (variable), no.
For example, if line 1 is 10 characters, and line 2 is 20 characters, then there is no way to calculate where line 3 is going to start without iterating through lines 1 and 2.
Operating systems aren't magic; if this kind of functionality was supported, they'd have to iterate through the file first as well. Either way, you're going to be looping through the contents.
Now, if the line lengths are guaranteed to be the same, that's a different story.
Say you have a text file like so:
AAAAAAA
BBBBBBB
CCCCCCC
Each line in the above text file is 7 characters. Assuming your line terminator is \n, each line takes up exactly 8 bytes.
In this case, you can safely fread() 8 bytes at a time and know that you're getting exactly one line. In order to jump to a particular byte in a file, you would use fseek().
Since you know the length of the lines in this scenario, you could jump to line N by simply doing
fseek(fp1, S * N, SEEK_SET);
where N is the line number (starting at 0) and S is the length of the line (as mentioned above, 8 bytes in our example file).
Note that the second solution will break if you're using a multi-byte encoding such as Unicode. Keep that in mind.
Using fgets() i made program, try it.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1, *fp2;
char ch,*str,*r;
int i =0;
int n = 0;
int l;
fp1 = fopen("co.data", "r");
fp2 = fopen("Output.txt", "w+");
printf("please enter how many lines do not need to be copied\n");
scanf ("%d", &l);
while (1)
{
if(r=fgets(str, 500, fp1))
{ /* a loop to read/copy the file*/
i++;
}
if (r == NULL)
break;
else if (i > l)
fputs(str, fp2);
}
printf("File copied Successfully!\n");
printf("number of lines read is %d\n",i-1);
printf("number of lines copied is %d\n",i-1-l);
fclose(fp1);
fclose(fp2);
}
I am writing a very simple editor. I have it so that the program reads from stdin and then prints to stdout right now (see code below). I want a program that will take in a file, and then depending on the command either print or append more text to the file. I am still confused how to do this after reading related questions. Do I use both scanf to read the file and then printf to print into the same file? Any clarification is much appreciated.
#include <stdio.h>
#define MAX_LINES 10
char text[MAX_LINES][MAX_LINES];
int main(void){
FILE *infile;
infile = fopen("file.txt", "w");
//check for file
if(infile==NULL){
puts("Error--no file found");
}
int count, x, y;
printf("Enter to quit the program.\n");
for(count=1; count<MAX_LINES+1; count++){
printf("%d: ", count);
fgets(text[count], MAX_LINES, stdin);
}
for(x=0; x<count; x++){
for(y=0;text[x][y];y++){
putchar(text[x][y]);}
putchar('\n');
}
fclose(infile);
return 0;
//end program
}
Your program does not "read from stdin", it reads from a named file, but, does not write to that file.
And here is another confusion
char text[MAX_LINES][MAX_LINES];
This would be better as
#define MAX_LINES 10
#define MAX_LENGTH 1000
...
char text[MAX_LINES][MAX_LENGTH];
Next, look at this loop
for(count=1; count<MAX_LINES+1; count++)
This will ignore the 0th element of the array and go out of bounds with the last. It should be
for(count=0; count<MAX_LINES; count++)
This is for stdin, but if the file is an opened disk file, say infile you should check if the read hits the end of the file
fgets(text[count], MAX_LINES, infile);
and replace with with
if (fgets(text[count], MAX_LENGTH, infile) == NULL)
break;
Your commented question Is there a way to both read from infile and add the text to infile? Yes but it's unviable, as #JonathanLeffler wrote "prepare a new file first".
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;
}