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.
I have written this C program, where it takes system calls as input like ps -f or ls /tmp, etc and output from the system call is pushed to a file and then from the file it reads and displays the output.
Here output file is getting created /tmp/j but there is no data present inside it. Can some one please help me with this issue and Thanks in advance.
My program.
#include<stdio.h>
#include<sys/syscall.h>
#include <stdlib.h>
main()
{
enum msgtype {PROCESS_LIST_REQUEST=1, PROCESS_LIST_RESPONSE, DIRECTORY_LIST_REQUEST, DIRECTORY_LIST_RESPONSE, ERROR_REQUEST};
struct head{
int version;
int msg_length;
int header_length;
enum msgtype msg_type;
char data;
char *reqtype;
};
struct head *buf;
char buff[10];
buf = malloc((sizeof(struct head)));
buf->reqtype=malloc(40);
char req[10];
printf("type ps -f on the console \n");
fgets(req, sizeof(req),stdin);
buf->reqtype = req;
printf("%s" , buf->reqtype);
snprintf(buff, sizeof(buff), "%s>/tmp/j", buf->reqtype);
printf("%s \n",buff);
system(buff);
{
FILE *fp;
char c;
fp = fopen("/tmp/j", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else
{
do {
c = getc(fp); /* get one character from the file*/
putchar(c); /* display it on the monitor*/
} while (c != EOF); /* repeat until EOF (end of file) */
}
fclose(fp);
}
}
There are a couple of errors in your code.
1) Allocate some memory greater than 10 for your buff. 10 is not enough. Your string is exceeding the size of 10. I made it 20 in my machine and checked.
2) fgets(req, sizeof(req),stdin); is reading a \n at the end of the string. Delete the last character. req[strlen(req) - 1] = '\0';
See this for man page of fgets
I have a script in C that reads a file structured in lines like this:
1,example,2,3;
2,exampl,3,5;
3,examp,7,4;
4,exam,9,1;
And the script is here:
while(fscanf(fptr,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
fscanf(fptr,"%d,%[^/,],%d,%s;", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon);
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
The problem I have is, that it reads only even lines of the file (2nd, 4th, 6th, 8th)...
How should I edit the code so it would read all lines?
Thanks for any help.
UPDATE1:
void nacti(emp *p,int n)
{
FILE *fptr;
fptr=fopen("ulozka.txt","r");
if(fptr==NULL){
printf("Error opening file!");
getchar();
}
typedef struct
{
int id;
char nojm[32];
int salar;
char phon[32];
} data_t;
int i = 0;
data_t m[4];
while(fscanf(fptr,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
printf("%d,%s,%d,%s\n", m[4].id,m[4].nojm,m[4].salar,m[4].phon);
//printf("%d",pocet);
}
If there is only m[4], the code will only read 4 lines of the file? How should I edit it to read "indefinit" number of lines?
Your code should be replaced with the following:
while(fscanf(fptr,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
The fscanf call in the while loop condition will be executed every loop iteration, so you don't need to call it again inside the loop.
UPDATE:
The following solution works for me. You can try it here.
#include <stdio.h>
typedef struct
{
int id;
char nojm[32];
int salar;
char phon[32];
} data_t;
int main(void) {
int i = 0;
data_t m[4];
while(fscanf(stdin,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
return 0;
}
I'm guessing the reason you're receiving a runtime error is that the character arrays you're using for strings (nojm and phon) are not long enough to process some of the entries in your text file, so memory is getting overwritten. Try increasing whatever length you're using to make sure it's greater than the longest string you'll encounter in your text file.
Another possibility is that you don't have enough items in your array to read in all the data from the text file. Here, I have a static array of 4 items to support the 4 from the text file. If your text file contains, say, 10,000 items you need to make sure you've properly allocated memory to store all of that.
You have
while(fscanf(fptr,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
fscanf(fptr,"%d,%[^/,],%d,%s;", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon);
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
So you:
read with fscanf()
read with fscanf()
print what you read
As a result you print only what the second fscanf read. Delete the second one and you should be fine.
So, your code should be like this:
while(fscanf(fptr,"%d,%[^/,],%d,%s", &m[i].id,m[i].nojm,&m[i].salar,m[i].phon) != EOF) {
printf("%d,%s,%d,%s\n", m[i].id,m[i].nojm,m[i].salar,m[i].phon);
i++;
}
I see that you have problems compiling your code. I suspect that your code is relevant to my example, it might help.
#include <stdio.h>
#include <string.h>
/* Define the struct before main. */
struct person {
char phon[20];
int id;
};
// Give a synonym. Now struct person is the same with person_t.
typedef struct person person_t;
int main(void) {
person_t array[3]; // can hold 3 persons
FILE* fptr = NULL;
fptr = fopen("test.txt", "r");
int i = 0;
while (fscanf(fptr, "%d, %s", &array[i].id, array[i].phon) != EOF) {
printf("%d, %s\n", array[i].id, array[i].phon);
i++;
}
return 0;
}
and the test.txt
1, 697555555
2, 697888888
3, 694777777
I have a program:
#include <stdio.h>
#include <string.h>
// ne menuvaj ovde
void wtf() {
FILE *f = fopen("text.txt", "w");
char c;
while((c = getchar()) != EOF) {
fputc(c, f);
}
fclose(f);
}
int main() {
wtf();
FILE *vlezna;
vlezna=fopen("text.txt","r");
float words=0,lines=0,average=0;
int counter=0;
char ch;
while((ch=fgetc(vlezna))!=EOF)
{
if(ch==' ')
words++;
if(ch=='\n');
{
words++;lines++;
}
}
average=words/lines;
printf("%f",average);
fclose(vlezna);
vlezna=fopen("text.txt","r");
while((ch=fgetc(vlezna))!=EOF)
{ words=0;
if(ch==' ')
words++;
if(ch=='\n')
{
words++;
if(words<average) counter++;
}
}
fclose(vlezna);
printf("%d",counter);
}
So i presume the first function writes to the file. But i guess the file should be created first, and i don't know how(except with right click new text document).
Also i didn't know how to return the pointer at the beginning of the file so i closed it and opened it again presuming that that will return the pointer at the beginning?
fopen create the file if it does not exist if option is "w".
Read the documentation here : http://www.cplusplus.com/reference/cstdio/fopen/
There is no need to create. For the man page of fopen:
``w'' Truncate to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
To set the file pointer use fseek. However, to read and write you need different open flags.