How to use fgetc to read a file - c

I am sorry the question was not very clear and the code i have so far is shown below and i am just stuck on how i can use the while loop to print the contents of the file.
#include<stdio.h>
int main()
{
FILE *number;
/* Open the file 'numbers' for reading */
number = fopen("numbers.dat", "r");
if (number != NULL) {
/* A bit of space for a line of text */
char lineOfText[100];
while (fgetc(lineOfText, 100, number) != NULL) {
printf("%s\n", lineOfText);
}
fclose(number);
}
/* sorry, my question was not clear and to clarify i am trying to
Print out the contents of the file with one entry per line, my .dat file includes
1,2,3,4,5,6,7,8,9 and i am trying to print them out in this format
1
2
3
4 and so on...
*/

To start you off...
FILE * f;
int c;
f=fopen ("numbers.txt","r");
while((c = fgetc(f)) != EOF) printf("%c", isdigit(c)? c : ' ');
fclose (f);

Related

How do I run C code on linux with input file from command line?

I'm trying to do some simple tasks in C and run them from the command line in Linux.
I'm having some problems with both C and running the code from the command line with a given filename given as a parameter. I've never written code in C before.
Remove the even numbers from a file. The file name is transferred to
the program as a parameter in the command line. The program changes
this file.
How do I do these?
read from a file and write the results over the same file
read numbers and not digits from the file (ex: I need to be able to read "22" as a single input, not two separate chars containing "2")
give the filename through a parameter in Linux. (ex: ./main.c file.txt)
my attempt at writing the c code:
#include <stdio.h>
int main ()
{
FILE *f = fopen ("arr.txt", "r");
char c = getc (f);
int count = 0;
int arr[20];
while (c != EOF)
{
if(c % 2 != 0){
arr[count] = c;
count = count + 1;
}
c = getc (f);
}
for (int i=0; i<count; i++){
putchar(arr[i]);
}
fclose (f);
getchar ();
return 0;
}
Here's a complete program which meets your requirements:
write the results over the same file - It keeps a read and write position in the file and copies characters towards the file beginning in case numbers have been removed; at the end, the now shorter file has to be truncated. (Note that with large files, it will be more efficient to write to a second file.)
read numbers and not digits from the file - It is not necessary to read whole numbers, it suffices to store the write start position of a number (this can be done at every non-digit) and the parity of the last digit.
give the filename through a parameter - If you define int main(int argc, char *argv[]), the first parameter is in argv[1] if argc is at least 2.
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc < 2) return 1; // no argument given
FILE *f = fopen(argv[1], "rb+");
if (!f) return 1; // if fopen failed
// read, write and number position
long rpos = 0, wpos = 0, npos = 0;
int even = 0, c; // int to hold EOF
while (c = getc(f), c != EOF)
{
if (isdigit(c)) even = c%2 == 0;
else
{
if (even) wpos = npos, even = 0;
npos = wpos+1; // next may be number
}
fseek(f, wpos++, SEEK_SET);
putc(c, f);
fseek(f, ++rpos, SEEK_SET);
}
ftruncate(fileno(f), wpos); // shorten the file
}
I'd do that like this (removing extra declarations => micro optimizations)
/**
* Check if file is avaiable.
*/
if (f == NULL)
{
printf("File is not available \n");
}
else
{
/**
* Populate array with even numbers.
*/
while ((ch = fgetc(f)) != EOF)
ch % 2 != 0 ? push(arr, ch); : continue;
/**
* Write to file those numbers.
*/
for (int i = 0; i < 20; i++)
fprintf(f, "%s", arr[i]);
}
Push implementation:
void push(int el, int **arr)
{
int *arr_temp = *arr;
*arr = NULL;
*arr = (int*) malloc(sizeof(int)*(n - 1));
(*arr)[0] = el;
for(int i = 0; i < (int)n - 1; i++)
{
(*arr)[i + 1] = arr_temp[i];
}
}
In order to write to the same file, without closing and opening it, you should provide both methods, w+ (writing and reading), and this method will clear it's content.
So, change the line where you open the file, for this.
FILE *f = fopen ("arr.txt", "w+");
You should look for ways of implementing dynamic arrays (pointers and memory management).
With this example you could simply go ahead and write yourself, inside the main loop, a temporary variable that stores a sequence of numbers, and stack those values
Something like this (pseudocode, have fun :)):
DELIMITER one of (',' | '|' | '.' | etc);
char[] temp;
if(ch not DELIMITER)
push ch on temp;
else
push temp to arr and clear it's content;
Hope this was useful.

How to take first row from this list of text?

I have a list of columns containing text but I just to fetch first upper row from this list. How to do that?
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
Your stop condition is EOF, everything will be read to the end of the file, what you need is to read till newline character is found, furthermore EOF (-1) should be compared with int type.
You'll need something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fr;
int c;
if(!(fr = fopen("prog.txt", "r"))){ //check file opening
perror("File error");
return EXIT_FAILURE;
}
while ((c = fgetc(fr)) != EOF && c != '\n')
{
printf("%c",c); /* display on screen*/
}
fclose(fr);
return EXIT_SUCCESS;
}
This is respecting your code reading the line char by char, you also have the library functions that allow you to read whole line, like fgets() for a portable piece of code, or getline() if you are not on Windows, alternatively download a portable version, and, of course you can make your own like this one or this one.
For whatever it's worth, here's an example that uses getline
#include <stdio.h>
int main()
{
FILE *fr;
char *line = NULL;
size_t len = 0;
ssize_t nread;
if (!(fr = fopen("prog.txt", "r"))) {
perror("Unable to open file");
return 1;
}
nread = getline(&line, &len, fr);
printf("line: %s, nread: %ld\n", line, nread);
fclose(fr);
return 0;
}
Some notes:
getline() can automatically allocate your read buffer, if you wish.
getline() returns the end of line delimiter. You can always strip it off, if you don't want it.
It's ALWAYS a good idea to check the status of I/O calls like "fopen()".
just replace EOF as '\n'(new line char). Than your code will read until reaching the new line. Here is what it looks like:
#include <stdio.h>
int main()
{
FILE *fr;
char c = ' ';
fr = fopen("prog.txt", "r");
while(c != EOF && c != '\n')
{
c = fgetc(fr); /* read from file*/
if(c != EOF){
printf("%c",c); /* display on screen*/
}
}
fclose(fr);
return 0;
}
I have not tested it yet but probably work. Please let me know if there is some problem with the code i will edit it.
Edit1:char c; in line 5 is initialized as ' ' for dealing with UB.
Edit2:adding condition (c != EOF) to while loop in line 7, for not giving reason to infinite loop.
Edit3:adding if statement to line 10 for not printing EOF which can be reason for odd results.

Complete equations from a text file in C

I need to write some code to read an equation from a text file and write the answer to a new one, and I'm completely stuck
I've managed to read the question and print it in terminal as characters, but that's it.
this new code can't even do that.
for those asking, the exact wording of the question is this:
"Read an input file: questions.txt; and produce a program that creates an output file answers.txt that includes
the question and the answer for each line in the questions file.
For example, if the line in questions is:
5*5
the answer file should read:
5*5 = 25
Allow for the following operations: +, -, *, /, % and for the correct order of operations. Also allow for at least 2
operators (3 operands), for example:
3+5*5 = 28"
My main problem is reading the equation from the text file and separating it into numbers and the operator symbol
FILE *fp;
int a, b, c, ch, i, number[100];
char input[5];
fp = fopen ("questions.txt", "r");
while(1)
{
ch = fgetc(fp);
if (ch == EOF)
{
break;
}
else
{
input[i] = ch;
}
}
fclose(fp);
printf("%s", input);
}
There are errors:
check file has been open correcly: if (fp != NULL)
i = 0; on begin, now we dont know value
input[i] = ch; => input[i++] = (char)ch;
if (ch == EOF) => if (ch == EOF && i < 4) 4 because 5 - 1 and move this to const or macro
After break of while input[i] = '\0';
You need to open the file you want to read from in read mode with the normal fopen('questions.txt', 'r') like you did. Next, you need to fopen('newFile.txt', 'w') you want to write to in w write mode. Use a while loop to get each character of the questions.txt file with getc(fileToRead) while you haven''t hit the end of the questions.txt file, hence ... != EOF, and write to the newFile.txt. The printf("%c", c) is to print each character as you read it from questions.txt.
FILE *fileToRead, *fileToWrite;
int c;
//open the questions.txt file in read mode
*fileToRead = fopen ("questions.txt", "r");
//create newFile.txt and open it in write mode
*fileToWrite = fopen ("newFile.txt", "w");
while ((c = getc(fileToRead)) != EOF) {
putc((char)c, fileToWrite );
printf("%c", (char)c);
}
fclose(fileToRead);
fclose(fileToWrite);

Opening Files in C

Full Edit:
I am getting frustrated, I don't know what am I doing wrong in here
I still have so many stuff to do in the code but I can't even open a file to continue my work.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char letter;
FILE *fp;
fp=fopen("‪‪‪C:\\Users\\LENOVO\\Desktop\\data.txt","r");
if(fp==NULL)
{
printf("error");
getch();
exit(1);
}
while(fscanf(fp,"%d",&letter)!=EOF)
putchar(letter);
getch();
fclose(fp);
}‪
Picture of the path: http://imgur.com/a/YwFYy
Still prints error
Ok, firstly let's take a look at your file path. There are two ways to acces a file from your local storage:
relative addresses if the file has the same root folder as your application
absolute addresses if the file is in a determined place on your machine's storage
I see that you are trying to use an absolute address to read from your file. Your path is correct but you have to take care about string formatting in C because the \ character could be interpreted as something else.
I would suggest to use this instead ( double back-slash )
input=fopen("‪C:\\Users\\LENOVO\\Desktop\\data.txt","r");
This will prevent string formatting interpretations.
Secondly, EOF is just a predefined macro constant and i think it is equal to -1 so your while(! (-1) ) code is not a good ideea for reading until the end of the file.
In order to read from a file until you reach the its end i would consider this property of fscanf() :
fscanf() returns EOF when it reaches the end of the file.
while(fscanf(input,"%ch",&letter) != EOF) {
putchar(letter);
}
This way of reading from a file should do the job.
To read everything from a text file and store its contents into a buffer:
First, you should count how many characters there are in the text file:
size_t get_file_len(FILE *fp)
{
size_t num = 0;
while (fgetc(fp) != EOF)
num++;
return (fseek(fp, 0, SEEK_SET) == 0 ? num : 0);
}
Then allocate memory for a buffer large enough and read all the characters:
char *load_text(const char *path)
{
char *buf = NULL;
FILE *fp = NULL;
size_t num = 0;
size_t i = 0;
int c = 0;
/* open the file in text mode */
fp = fopen(path, "r");
if (!fp)
return NULL;
/* if the file was empty or if an error occurred, return error */
if ((num = get_file_len(fp)) == 0) {
fclose(fp);
return NULL;
}
buf = malloc(num + 1);
if (!buf) {
fclose(fp);
return NULL;
}
while ((c = fgetc(fp)) != EOF)
buf[i++] = (char)c;
/* ensure that the string is null-terminated */
buf[i] = '\0';
fclose(fp);
return buf;
}
Also, in C, all escape sequences begin with a '\' (backslash), so if you wanted to write a backslash in a string or a char you should write it as a '\\' (double backslash):
input=fopen("‪C:\\Users\\LENOVO\\Desktop\\data.txt","r");
pretty simple here :
while(!feof(input)){
fscanf(input,"%c",&letter);
putchar(letter);
}
and remember to close file using fclose(input);

C language, read new line character from external file

Hello guys i have an external file like this :
I want to read all character (include space and new line) to my 2-Dimensional(row and column) array, but i failed to do that. Example, in that file at line 10 and column 1 (the bottom left corner) there is a '/' character. I want to put '/' in my array[9][0] (index in array start from 0 not 1), so every character is located in array as same as the file.
Here is my code :
#include <stdio.h>
int main(void) {
/** my index array variable, i for row and j for column */
int i;
int j;
/** varible to read character */
char c;
/** array for the input. The file will not consist more than 17 rows and 2017 columns*/
char input[17][2017];
/** pointer to a file */
FILE *fp;
/** read that file. (my code and that file are located in the same place) */
fp = fopen("bangun.in", "r");
/** start reading the file */
i = 0;
j = 0;
while ( (c = fgetc(fp)) != EOF){
if (c != 0) {
input[i][j]=c;
}
else if (c == '\n') {
input[i][j]=c;
printf("get in");
i++;
}
j++;
}
fclose(fp);
return 0;
}
if my algoritm is worng, could you tell me how to it? my aim is copy all character with the position into my array.
Your if logic is wrong, if c == 0 (else condition) it will never be a new line.

Resources