File handling in c - c

I made a simple program to read the no of values and then, those values from file and storing them in an array and print the values of array.
#include<stdio.h>
#include<stdlib.h>
void main(){
int i=0,j=0,n,no[n];
FILE *fp=fopen("input.txt","r");
if(fp==NULL)
printf("File input error\n");
else{
fscanf(fp,"%d",&n);
*no=(int *)malloc(n*sizeof(int));
while(i<n){
fscanf(fp,"%d",&no[i]);
printf("%d\t",no[i]);
i++;
}
}
}
My input file was as follows
10 37 21 55 52 68 97 02 00 103 84
and the output I got is
37 21 55 52 68 97 2 0
Why do I see this output?

The line
*no=(int *)malloc(n*sizeof(int));
is not right. I am surprised your compiler didn't warn you.
*no is of type int. You are assigning a pointer to an int.
Using gcc, I get the following warning.
soc.c: In function ‘main’:
soc.c:11:12: warning: assignment makes integer from pointer without a cast
*no=(int *)malloc(n*sizeof(int));
Also, the line
int i=0,j=0,n,no[n];
is not correct. n is not initialized before being used to define no.
Here's an updated version of your program that should work.
#include<stdio.h>
#include<stdlib.h>
void main(){
int i=0,j=0,n;
int* no;
FILE *fp=fopen("input.txt","r");
if(fp==NULL)
printf("File input error\n");
else{
if ( fscanf(fp,"%d",&n) == 1 )
{
no = malloc(n*sizeof(int));
while(i<n){
if ( fscanf(fp,"%d", &no[i]) == 1 )
{
printf("%d\t",no[i]);
}
else
{
// Unable to read the number.
// Get out of the loop.
break;
}
i++;
}
}
else
{
// Unable to read n.
// Print some message to indicate the error
}
}
}

In your code, you are trying to read n elements without checking for EOF.
You should add a condition comparing fscanf with number of scanned elements (in this case 1) and therefore avoid reaching EOF unknowingly.

Related

text files in C language [duplicate]

I made a simple program to read the no of values and then, those values from file and storing them in an array and print the values of array.
#include<stdio.h>
#include<stdlib.h>
void main(){
int i=0,j=0,n,no[n];
FILE *fp=fopen("input.txt","r");
if(fp==NULL)
printf("File input error\n");
else{
fscanf(fp,"%d",&n);
*no=(int *)malloc(n*sizeof(int));
while(i<n){
fscanf(fp,"%d",&no[i]);
printf("%d\t",no[i]);
i++;
}
}
}
My input file was as follows
10 37 21 55 52 68 97 02 00 103 84
and the output I got is
37 21 55 52 68 97 2 0
Why do I see this output?
The line
*no=(int *)malloc(n*sizeof(int));
is not right. I am surprised your compiler didn't warn you.
*no is of type int. You are assigning a pointer to an int.
Using gcc, I get the following warning.
soc.c: In function ‘main’:
soc.c:11:12: warning: assignment makes integer from pointer without a cast
*no=(int *)malloc(n*sizeof(int));
Also, the line
int i=0,j=0,n,no[n];
is not correct. n is not initialized before being used to define no.
Here's an updated version of your program that should work.
#include<stdio.h>
#include<stdlib.h>
void main(){
int i=0,j=0,n;
int* no;
FILE *fp=fopen("input.txt","r");
if(fp==NULL)
printf("File input error\n");
else{
if ( fscanf(fp,"%d",&n) == 1 )
{
no = malloc(n*sizeof(int));
while(i<n){
if ( fscanf(fp,"%d", &no[i]) == 1 )
{
printf("%d\t",no[i]);
}
else
{
// Unable to read the number.
// Get out of the loop.
break;
}
i++;
}
}
else
{
// Unable to read n.
// Print some message to indicate the error
}
}
}
In your code, you are trying to read n elements without checking for EOF.
You should add a condition comparing fscanf with number of scanned elements (in this case 1) and therefore avoid reaching EOF unknowingly.

Copying chars from file into an array

txtfile.txt is a file with 30 lines, each line having 50 characters.
I need to copy each character from txtfile into into Carray. How can I do this? I get a segmentation fault when I try.
I have tried the most obvious approach, which is just copying c into the array.
int cArray[29][49];
fp = fopen("input_blinker.txt", "r");
if(fp==NULL){
perror("Error in opening file");
return(-1);
}
int columnInd = 0;
int rowInd = 0;
do {
c = fgetc(fp);
if (feof(fp)) {
break;
}
cArray[rowInd][columnInd] = c;
columnInd++;
if (columnInd > 29){
rowInd++;
columnInd=0;
}
} while(1);
fclose(fp);
return(0);
I expect the value of c will be copied into the given index of cArray, but I know that isn't correct. Once again, I am getting segmentation fault. Thanks for any help (still learning c)
Your array isn't big enough:
int cArray[29][49];
This creates a 2D array of size 29 x 49. You need an array of 30 x 50:
int cArray[30][50];
Your bounds checks are also incorrect:
cArray[rowInd][columnInd] = c;
columnInd++;
if (columnInd > 29){
rowInd++;
columnInd=0;
}
The size of the second dimension is 49, 50 after fixing it, so you should be checking that value. You should also put in a check to make sure your row index doesn't exceed the bounds of the array.
if (columnInd >= 50){
rowInd++;
columnInd=0;
}
if (rowInd >= 30) {
break;
}

How to read space-separated values in C?

I have a .txt file that I am using to learn some basic C.
Here is the txt file:
8
12 48 15 65 16 82 9 72
Here is my C program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
char num = 0;
//int[] arr = 0;
if (argc != 2){
return 0;
}
FILE *inputFile = fopen(argv[1], "r");
if (inputFile == NULL){
printf("Error1\n");
return 0;
}
while(!feof(inputFile)){
num = fgetc(inputFile);
printf("%c\n",num);
}
if(!feof(inputFile)){
printf("error");
return 0;
}
}
My goal is the get an array of the second line, based on the amount of values in the first line.... essentially, we want an array with 8 values, that stores {12, 48, ....}
You are using a wrong function to read integers: in spite of returning an int, function fgetc is reading individual characters (why getchar returns an int?).
In order to read space-separated integers, use fscanf instead, and check the return value to decide that you have reached the end of file:
int n;
while (fscanf(inputFile, " %d", &n) == 1) {
printf("%d\n", n);
}
Note that the loop above avoids using feof to detect the end of file condition (why using feof is wrong?)
If you aim to read a series of numbers (and nothing else), regardless of the number of line breaks in between, you could simply use fscanf as follows:
int num;
while(fscanf(inputFile, "%d", &num) == 1) {
printf("%d\n",num);
}
Note that fscanf returns the number of values successfully read in according to the format specifier, i.e. it returns 1 as long as an integral value could have been read in (and 0 otherwise).

error: used struct type value where scalar is required

I am creating a program which takes an input and opens a text file and changes words to lower or upper case depending on what the user wants. When I compile the program I gets the following error:
22:11: error: used struct type value where scalar is required
30:11: error: used struct type value where scalar is required
1 #include <stdio.h>
2 int main(void) {
3
4 char choice;
5 char fileName;
6 char newFileName;
7 int i = 0;
8
9 printf("Change Case \n");
10 printf("============\n");
11 printf("Case (U for upper, L for lower) : ");
12 scanf(" %c", &choice);
13 printf("Name of the original file : oldFile.txt \n");
14 printf("Name of the updated file : newFile.txt \n");
15
16 FILE *fp = NULL;
17
18 fp = fopen("oldFile.txt", "a");
19
20 if (fp != NULL && choice == 'L') {
21
22 while ( fp[i] ) {
23
24 putchar(tolower(fp[i]));
25 i++;
26 }
27 }
28 else if (fp != NULL && choice == 'U') {
29
30 while ( fp[i] ) {
31
32 putchar(toupper(fp[i]));
33 i++;
34 }
35 }
36 else {
37
38 printf("ERROR: No proper choice was made \n");
39 }
40 }
fp is a file pointer, not an array of whats in your file. Have a look at use of fopen in a tutorial.
You will need to use something like fgets to read your file into a buffer. You can also use fgetc to read your file one character at a time.
wrong way accessing file pointer fp. It is an pointer to a file not a array character or string. Each time a file is opened, the system places the file pointer at the beginning of the file, which is offset zero.
Close the opened file every time after processing using fclose(fP);
sample example code snippet of using file pointer.
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);// or fgets as per the usage
if( c==EOF)
{
//Exit
}
// your code
}
fclose(fp);
The file pointer is not an array... consider using fgetc/fgets. fp[i] doesn't give you the i-th byte of the file. fgetc will let you iterate over the bytes of the file and return EOF when you're at the end.
See the documentation for fgetc here.
Here is an example on how to acquire strings from txt. There are many other ways
#include <stdio.h>
int main(void) {
FILE *fp;
fp = fopen("oldFile.txt", "r");
char str[1024];
while(fgets(str, 1024, fp)!=NULL) { //acquire strings from oldFile.txt through fgets() which returns a pointer. NULL is returned at the end of file
printf("%s", str); //just an example
}
}

program that writes the even and odd numbers

I was writting a program that can read a set of numbers file called dog.txt;
and also writes to two file separating odd and even. i was able to compile my program however, the output expected is not the same which was supposed to be even numbers in one file called EVEN, odd numbers in file odd.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int even,odd;
int num;
if (argc != 4) {
printf("Usage: executable in_file output_file\n");
exit(0);
}
FILE *dog = fopen(argv[1], "r");
FILE *feven= fopen(argv[2], "w");
FILE *fodd= fopen (argv[3], "w");
while (fscanf(dog, "%d", &num) != EOF)
{
if (0==i%2){
i++;
printf("even= %d\n", num);
}
else if(i!=0){
i++;
printf("odd= %d\n", num);
}
}
fclose(feven);
fclose(fodd);
fclose(dog);
return 0;
}
output:
even= 1
odd= 2
even= 34
odd= 44
even= 66
odd= 78
even= 94
odd= 21
even= 23
odd= 54
even= 44
odd= 65
even= 78
odd= 68
even= 92
You're checking i % 2, not num % 2. I'm not even sure what i does in this example—perhaps you're planning on using it later.
while (fscanf(dog, "%d", &num) != EOF) {
if (num % 2 == 0) {
printf("even = %d\n", num);
}
else if(num != 0) {
printf("odd = %d\n", num);
}
}
I imagine the code to write these numbers to the files will come later, once you've fixed this bug.
The code contains no instructions to write into the output files. It only writes to stdout.
In addition to the printf/fprintf problem, in any decent modern compiler, that code should be generating a warning that you're not assigning any initial value to i.
The printf function writes to the screen (more correctly, it writes to "standard output", but that is usually the screen). You want to write to a file. You have opened files called feven and fodd. To write to them, you would use the fprintf call, which works like printf except it takes an extra (left-most) argument, which is the FILE* that you want to write to, e.g.
FILE *fmyfile = fopen("myfile.txt", "w");
fprintf(fmyfile, "The magic number is %d!", 3);
Also, your results are incorrect, but that's an unrelated problem.

Resources