print 5 lines from input file - c

currently, I am writing code in c program for printing small portion of contents from the input file. Actually, in my code I can able to print just one single line. but, i have to print next 5 lines after that one line.
I am new to programming, please help to solve this problem**
code is given below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lineNumber = 2;
int main()
{
FILE *file;
char line[100];
int count = 0;
///Open LS-dyna file to read
file = fopen("P:\\tut_c\\read\\df-read\\in.txt", "r");
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
else if ( file != NULL )
{
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
if (count == lineNumber)
{
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}

The first logical error occurs in your while loop, first iteration, when you close the file and return 0.
Next, there is no reason to have a counter for your lines, since there are many c functions that can handle finding the end of file (eof).
Instead:
Use a while loop for iteration through the file.
Use a standard library c function for file reading.
Check if file has reached the end.
If the line is still valid, then print the line.
Here is some code to reiterate:
int main()
{
FILE *file;
file = fopen("file.txt", "r");
if (!file){ // check if file exists
perror("fopen");
exit(EXIT_FAILURE);
}
else { // if file exists, then...
char line[256];
while(fgets(line, sizeof line, file)){
printf("\n str %s ", line);
}
fclose(file);
}
return 0;
}// end main

Related

C program to print given number of lines from beginning of text file. File name and number of lines from command line argument

I'm writing a program said in this post title. I take reference at this webpage.
https://www.includehelp.com/c-programs/c-program-to-print-given-number-of-lines-of-a-file-like-head-command-in-linux.aspx
Here are the codes from that webpage.
#include <stdio.h>
int main(int argc, char * argv[])
{
FILE *fp; // file pointer
char *line = NULL;
int len = 0;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (getline(&line, &len, fp) != -1)
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line); fflush(stdout);
}
// close file
fclose(fp);
return 0;
}
My problem is the getline function. Since I'm not using Linux that function's giving error in my compiler. I tried to change it to fgets function. This is my revised codes.
I got two errors in the line ' while (fgets(&line, bufferLength, fp) != -1)'.
Error: passing argument 1 of 'fgets' from incompatible pointer type.
Error: comparison between pointer and integer.
My question is - how can I modify the program using fgets? Many thanks to anyone who can work this out.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fp; // file pointer
char *line = NULL;
int bufferLength = 255;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (fgets(&line, bufferLength, fp) != -1)
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line);
fflush(stdout);
}
// close file
fclose(fp);
return 0;
}
Your program should compile and run correctly follows:
//c program to print given number of lines from beginning of a file
//file name and number of lines must be supply as command line argument
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
FILE* fp; // file pointer
char* line = malloc(255);
int bufferLength = 255;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (fgets(line,bufferLength, fp))
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line);
fflush(stdout);
}
// close file
fclose(fp);
free(line);
return 0;
}
we have two main problems, first
char * line = NULL;
line is a line of characters, a string if you want to call it that, so we must reserve enough memory to accommodate a complete line, and we do this with the malloc function, as seen in the program, the other problem we have with fgets, this function returns a pointer therefore we cannot compare the value returned by fgets with an integer, the declaration
while (fgets (line, bufferLength, fp))
is equivalent to running the loop while fgets is other than NULL. Finally we must use line instead of &line, the latter asks for the address of the line pointer, and not the address it points to.
There's no need to keep track of more than a single character. Reading full lines is overkill. Just do:
#include <stdio.h>
#include <stdlib.h>
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = fopen(path, mode);
if( fp == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
int
main(int argc, char **argv)
{
int count = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
FILE *in = argc > 2 ? xfopen(argv[2], "r") : stdin;
int line = 0;
int c;
while( line < count && ( c = fgetc(in)) != EOF ) {
putchar(c);
if( c == '\n' ) {
line += 1;
}
}
}
Note that I've reversed the order of the arguments, so that stdin is read if only a count is given.

Reading a file, modifiying each line, storing it into a buffer, printing all at once

This is the file:
line 1
line 2
line 3
How to read the file line by line...
Append a suffix to each line..
FILE *fp = fopen ("file", "r");
while (fgets (buffer, sizeof (buffer), fp) != NULL) {
// append "test" to each line.
// store the result in a buffer named "result"
}
fclose (fp);
print the result all at once:
printf( "%s", result );
Expected result :
line 1test
line 2test
line 3test
The below program might do the requirement but it is not efficient enough. I am just giving a rough example. Hope this helps.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void display(char** temp,int LinesWritten);
int main()
{
FILE *fp;
char *buffer = (char*)malloc(sizeof(char)*101); // 101 is just an assumption. dynamic size may be decided
char **result = (char**)malloc(sizeof(char*)*10); // 10 is just an assumption. dynamic size may be decided
int LinesWritten = 0;
char **temp = result;
char **freetemp = result;
if((fp = fopen("file.txt","r"))==NULL)
{
printf("Error while opening file\n");
exit(1);
}
while((fgets(buffer,100,fp))&&(!(feof(fp)))) //assuming that 100 characters will be read into the buffer
{
if(*result = (char*)malloc(sizeof(char)*10))
{
sprintf(*result,"%s%s",buffer,"test");
*result++;
LinesWritten++;
}
}
fclose(fp);
display(temp,LinesWritten);
if(freetemp!=NULL)
{
free(freetemp);
}
return 0;
}
void display(char** temp,int LinesWritten)
{
for(int i=0;i<LinesWritten;i++)
{
printf("%s\n",*temp);
*temp++;
}
return;
}

Read one file and write to another C

I am trying to read from files and write to a temp file. However, I am stuck in an infinite loop right now. The function below is called multiple times by a recursive function that goes through directories to read files.
My approach is that I would read each word from one file, then those words to another file.
The function I have works fine if I just print out each word. It prints out each word in each file in all directories. However, when I try to start writing to a temp file (the code commented out), I am stuck in the while loop.
On the other hand, if I just call the function once in a test program where I just read from one file in the current directory, and write to a temp file, it's fine.
This is what I have (fileName when passed in is actually the absolute path, and I do ../tmp so it does not get caught in the recursion function):
void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
FILE *file = fopen(fileName, "r");
if (file != NULL) {
int ch, word = 0;
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch) || ispunct(ch)) {
if (word) {
word = 0;
putchar('\n');
}
}
else {
word = 1;
putchar(ch);
/*
FILE *f = fopen("../tmp", "wb"); // create and write
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "Some text"); // Or fprintf(f, ch);
fclose(f);
*/
}
}
fclose(file);
}
}
There's nothing in your code that suggests an infinite loop. However, if fileName is very large, you could be opening and closing "..\tmp" millions of times. As Joachim Pileborg points out in the comments, you should open that file just once at the beginning of your function, and close it again at the end.
If you want to convince yourself that you are not in an infinite loop, print out the value of ch on each iteration.
Okay so I did this and it worked. But I don't understand why though. Can someone explain it please?
void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
FILE *file = fopen(fileName, "r");
FILE *f = fopen("../tmp", "wb"); // MOVE HERE
if (file != NULL) {
int ch, word = 0;
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch) || ispunct(ch)) {
if (word) {
word = 0;
putchar('\n');
}
}
else {
word = 1;
putchar(ch);
/*
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "Some text"); // Or fprintf(f, ch);
*/
}
}
fclose(file);
fclose(f); // MOVE HERE
}
}

C File Reader from array

I can see the last printf output of y but the fpc turns null.
I suspected for double quotes in fopen function but not could not find a solution: how to fix it?
Part of the code ;
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST %s\n",y);
When I run the code;
Error opening file.
TEST /Users/lessons/AbstractLesson.java
Here is the full code;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
int main(void){
char *arr_lines, *line;
char buf_line[LINESIZE];
int num_lines = 0;
char buf[10240];
// open file
FILE *fp = fopen("/tmp/file", "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_line, LINESIZE, fp))
if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n'))
num_lines++;
// allocate memory
arr_lines = (char*)malloc(num_lines * 1024 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
line=arr_lines;
while (fgets(line, LINESIZE, fp))
if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n'))
line += LINESIZE;
// print first four lines
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST [%s]\n",y);
//x = &arr_lines[1024*0];
// y = *x;
// finish
fclose(fp);
return 0;
}
Change printf("TEST %s\n", y) to printf("TEST \"%s\"\n", y) so we can see if you have any extra whitespace characters in the filename.
fgets() returns the new line, if it's there. I didn't see where your code clears the newline. Does your path string include the new line?
Beyond that, fopen() is almost certainly working correctly. The only options are 1) The path is not correct, 2) the path has whitespace or other invalid characters, or 3) the file is not available for reading.
If you don't have a new line in your path, then you simply haven't provided enough information to resolve this issue.
I suspect the path, /Users/lessons/AbstractLesson.java, is wrong. It looks like an OSX path and it might be missing the username between Users and lessons.

Count tabs and check line lengths

I'm learning c by myself and I'm actually trying to code a program which count the numbers of TAb in a file and if a line has a tab, I want to print the whole line and the numbers of tabs in this line. And if it is not muhch more difficult, I want you to help me to do that also if a line has more than 80 characters, print this line and the numbers of characters
I have this main function:
include <stdio.h> /* printf */
/* Prototype from tablen.c */
void tablen(const char *filename);
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Usage: tablen filename\n");
printf("where: filename - file to process.\n");
return -1;
}
tablen(argv[1]);
return 0;
}
This main function is very basic so I hope there is no error there.
And this function too:
include <stdio.h> /* FILE, fopen, feof, fgets, fclose */
include <string.h> /* strlen */
void tablen(const char *filename)
{
/*Variables*/
int i; /*loop controller */
int tabs = 0; /*number of tabs*/
int line = 0; /*current line*/
int size_string; /*size of the string*/
File *file; /* open and read the file */
file = fopen(filename, "rt"); /*open the file for read text*/
size_string = strlen(filename);
/*if we can read the file*/
if(file)
{
/*while we don't reach the end of file, we still reading*/
while (!feof(file))
{
for(i = 0; i < size_string; i++)
{
if(filename[i] == 9) /*ASCII value of TAB is 9 or '\'*/
{
tabs++;
}
if(tabs > 0)
{
printf("# %i: (tabs: %i) |", line, tabs);
}
if(filename[i] == '\n')
{
line++;
tabs = 0;
}
}
}
}
}
I've write this pseudo-code, I think it is correct
For counting tabs:
First open a file for read/text
while there are more line in the file(and reading one by one) we count the number of tabs
if we found a line with tabs, print the line and the count of tabs
Of course we close the file
For checking line lengths
First open a file for read/text and hile there are more lines in the file, we heck the length of each line.
If the line is longer than 80 characters we print that line with length information
I don't know if I am in the correct way because is the first time I try to deal with files
For counting number of tabs in a line at a time, it is better to use getline() function.
getline() reads a line from file stream and returns number of characters in read line. Read manual page of getline() for more information.
You can take a look at below code for the solution to your problem
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
int tabs=0,totaltabs=0,i;
fp = fopen(argv[1], "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %d\n", read);
for(i=0;i<read;i++){
if(line[i] == '\t')
tabs++;
}
if(tabs){
printf("line = %s\nNumber of tabs = %d\n",line,tabs);
totaltabs = totaltabs+tabs;
tabs=0;
}
if(read >=80)
printf("%s\n",line);
}
if (line)
free(line);
exit(EXIT_SUCCESS);
}

Resources