How to read line wise from a file in c (Ubuntu)? - c

I'm trying to extract string line by line from a file but its giving me no output.The file has some words in a token wise.Here is my code :
#include<stdio.h>
#include<string.h>
main(void)
{
FILE *open;
open = fopen("assembly.txt", "r");
FILE *write;
write = fopen("tokens.txt", "w");
FILE *a;
char ch;
char *str;
while ((ch = fgetc(open)) != EOF)
{
if (ch == 32 || ch == ',' || ch == '#')
fprintf(write, "\n");
else
fprintf(write, "%c", ch);
}
a = fopen("tokens.txt", "r");
while (!feof(a))
{
if (fgets(str, 126, a))
printf("%s", str);
}
}
I'm getting no output at all.The program executes successfully without any output!

There are several errors in your code.
First: you didn't close the files.
Second: you did a fgets with str which has not been allocated which will segfault.
With the fixes, now your code is:
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *open;
open = fopen("assembly.txt", "r");
FILE *write;
write = fopen("tokens.txt", "w");
FILE *a;
char ch;
char str[127];
while ((ch = fgetc(open)) != EOF)
{
if (ch == 32 || ch == ',' || ch == '#')
fprintf(write, "\n");
else
fprintf(write, "%c", ch);
}
fclose(write);
fclose(open);
a = fopen("tokens.txt", "r");
while (!feof(a))
{
if (fgets(str, 126, a))
printf("%s", str);
}
fclose(a);
return 0;
}

Related

C program wrong output for reading a file

Hello guys so I write this program which purpose is to open a file and read how many characters has in it and print the line with the most and the least characters.I've made it into two functions one for the biggest line and one for the smallest.The "biggest line" function works just fine but I get wrong output for the smallest one.Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char f_view[150];
void ShowResults();
int leastsymbols();
int mostsymbols();
int main(){
ShowResults();
return 0;
}
int mostsymbols(){
FILE *fp;
fp=fopen(f_view, "r");
if(fp==NULL){
printf("Error\n");
exit(-1);
}
int lineNO=1;
int c;
int currCount=0;
int highestCount=0;
int highestline=0;
while ((c = getc(fp)) != EOF){
if (c == '\n') {
currCount=0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
if(currCount>highestCount){
highestCount=currCount;
if(lineNO>highestline){
highestline=lineNO;
}
}
}
}
fclose(fp);
return highestline;
}
int leastsymbols()
{
FILE *fp;
fp = fopen(f_view, "r");
if (fp == NULL)
{
printf("Could not open file \n");
exit(-1);
}
int c;
int lineNO = 1;
int currCount=0;
int leastLine=0;
int leastCount=1000;//assuming that a line in a file can not be longer
//than 1000 characters
while ((c = getc(fp)) != EOF){
if (c == '\n'){
currCount = 0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
}
if(currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
}
fclose(fp);
return leastLine;
}
void ShowResults()
{
FILE *fptr;
char *fix;
char c;
char openFile[1024];
printf("Type the destination to the *.c file or the file name.\n");
//the user has to enter a .C file
while(f_view[strlen(f_view) - 2] != '.' && f_view[strlen(f_view) - 1]
!= 'c')
{
fgets(f_view, 150, stdin);
fix = strchr(f_view, '\n');
if(fix != 0)
*fix = 0;
}
if((fptr = fopen(f_view, "r")) == NULL)
{
printf("Cannot open file !\n");
exit(-1);
}
int highestLine;
int lowestLine;
while (fgets(openFile, 1024, fptr))
{
highestLine=mostsymbols();
lowestLine=leastsymbols();
}
printf("Line %d has the most symbols.\n",highestLine);
printf("Line %d has the least symbols.\n",lowestLine);
fclose(fptr);
return ;
}
I fixed my program thank you.:)
while ((c = getc(fp)) != EOF){
if(c == '\n' && currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
if(c=='\n'){
currCount = 0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
}
}
move this check to when you go to the next line
if(currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
your placement is wrong because currCount is at the first iteration is still 1 or 0 depending on what is first character on the line, so it is the smallest and this is for every new line you read

Issues in string manipulation

The log.txt file consist of some data. The program looks for ":" and when it find it prints "Done". The program compiles successfully but never prints "Done".
char *atrbt ;
FILE *fp;
int i = 0;
if (fp = fopen("log.txt", "r+")) {
while (fscanf(fp, "%c", &atrbt) != EOF) {
printf("%c", atrbt);
if(atrbt[i] == ':') { <------------ Issue
printf("Done");
}
++i;
}
}
You are mixing between char and char pointers. One of the possible correct ways could be (code is untested):
char atrbt;
FILE *fp;
if (fp = fopen("log.txt", "r+")) {
while ((atrbt = getc(fp)) != EOF) {
printf("%c", atrbt);
if(atrbt == ':') {
printf("Done");
}
}
}

Find today's date in a .txt file and print line?

I have a small problem working with dates, whereas I need to print all lines in a .txt file containing the user's current date.
Here's my code:
//My function
int search(FILE *fp, char * str)
{
FILE *fp1;
fp1 = fopen("fp1","w");
char s[10],c;
int len = strlen(str);
int i = 0;
int d;
int seek = fseek(fp, 0, 0);
c = fgetc(fp);
while (c != EOF)
{
if (c == ' ' || c == '\n')
{
s[i] = '\0';
i = 0;
if (strcmp(s, str) == 0)
{
while (c = fgetc(fp) != '\n')
{
fseek(fp, -2L, 1);
d = ftell(fp);
}
while ((c = fgetc(fp)) != '\n')
{
fputc(c, fp1);
}
}
}
else
{
s[i] = c;
i++;
}
c = fgetc(fp);
}
return 1;
}
//int main function callback
printf("\n\nTasks due today("__DATE__"): \n");
FILE *tasks = fopen("tasks.txt", "r+");
search(tasks, __DATE__);
fclose(tasks);
Any idea on how to get this working?
Thank you.
Try this:
#include <stdio.h>
#include <string.h>
int search(FILE *fp, const char *str){
FILE *fp1;
fp1 = fopen("fp1","w");
if(!fp || !fp1 || !str || !*str)
return 0;
char line[128];
while(fgets(line, sizeof line, fp)){
if(strstr(line, str)){
fputs(line, fp1);
}
}
fclose(fp1);
return 1;
}
int main(void){
printf("\n\nTasks due today(\"%s\"): \n", __DATE__);
FILE *tasks = fopen("tasks.txt", "r");
search(tasks, __DATE__);//Note that __DATE__ is at the time of compilation.
fclose(tasks);
return 0;
}

How to write text from file to a string in C

I want to write code were the user is asked to write the name of a file. Then I want to analyze the file's content for a symbol, let's say 'e'.
My problem is that I don't know how to start analyzing the file the correct way so that the content can be checked.
int main() {
char c[1000], file_name[1000];
int i;
int s = 0;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
if ((fp = fopen(file_name, "r")) == NULL){
printf("Error! opening file");
exit(1);
}
if (fp) {
while (fscanf(fp, "%s", c) != EOF) {
printf("%s", c);
}
fclose(fp);
for (i = 0; c[i] != '\0'; ++i) {
puts(c);
if (c[i] == 'e') {
++s;
}
}
printf("\nWhite spaces: %d", s);
_getche();
return 0;
}
}
char line[512]; /*To fetch a line from file maximum of 512 char*/
rewind(fp);
memset(line,0,sizeof(line)); /*Initialize to NULL*/
while ( fgets(line, 512, fp ) && fp !=EOF)
{
/*Suppose u want to analyze string "WELL_DONE" in this fetched line.*/
if(strstr(line,"WELL_DONE")!=NULL)
{
printf("\nFOUND KEYWOD!!\n");
}
memset(line,0,sizeof(line)); /*Initialize to null to fetch again*/
}
If its just a symbol you're looking for, or a char, you can simply use getc() :
int c;
....
if (fp) {
while ((c = getc(fp)) != EOF) {
if (c == 'e') {
// Do what you need
}
}
Or, alternatively, if it's a word you're looking for, fscanf() will do the job:
int c;
char symb[100];
char symbToFind[] = "watever"; // This is the word you're looking for
....
while ((c = fscanf(fp, %s, symb)) != EOF) {
if (strcmp(symb, symbToFind) == 0) { // strcmp will compare every word in the file
// do whatever // to symbToFind
}
}
These alternatives will allow you to search every char or string in the file, without having to save them as an array.

Segmentation fault when printing out arrays

This is part of the program I am working on, it is copying the file opened and then put it into an array (file1). However, I am getting a segmentation fault when I try to print out the content of the file1.
I had tried to set the MAX_MAC_ADD to 50 and BIG_NUM to 30000 such that it is big enough to sustain the file from fgets().
The file which I am opening has 4 parts, each separate by a 'tab'
e.g. 1one 1two 1three 1four
2one 2two 2three 2four
char file1[MAX_MAC_ADD][BIG_NUM];
int num_MAC = 0;
char *Programe_Name;
int saperate_fields1(char line[])
{
int i = 0;
int f = 0;
while(line[i] != '\0' && line[i] != '\n')
{
int c = 0;
while(line[i] != '\t' && line[i] != '\0' && line[i] != '\n')
{
file1[f][c] = line[i];
++c;
++i;
}
file1[f][c] = '\0';
++f;
if(f == (MAX_MAC_ADD-1))
{
break;
}
++i;
}
return f,i;
}
void read_file1(char filename[])
{
//OPEN FOR READING
FILE *fp = fopen(filename,"r");
if(fp == NULL)
{
printf("%s: cannot open '%s'\n", Programe_Name, filename);
exit(EXIT_FAILURE);
}
char line[BUFSIZ];
while(fgets(line, sizeof line, fp) != NULL)
{
saperate_fields1(line); //SAPERATE INTO FIELDS
num_MAC = num_MAC + 1;
printf("%d times\n", num_MAC);
}
fclose(fp);
printf("line is:\n%s\n", line); //TO CHECK WHERE DO THE PROGRAM STOP READING
printf("file1 is:\n%s\n", file1);
}
You pass a pointer to an array of chars to the format specifier %s which expects a pointer to a char. If you want to print your array of arrays of char you need to print the elements individually, e.g.:
for (int i = 0; i != end; ++i) {
printf("file1[%d]='%s'\n", i, file1[i]);
}

Resources