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;
}
Related
whenever I run the program the second print statement isn't printing. I tried using a function but I'm new to C and don't really understand anything. I've also attached my activity as I'm not sure how to do the other things on it.activity photo
#include <stdio.h>
#include <string.h>
#define LINE_LENGTH 1000
int main(int argc, char **argv)
{
FILE *input_file = fopen("cstest.c", "r");
char line [LINE_LENGTH];
//while loop to ger
while (fgets(line, LINE_LENGTH, input_file) != NULL)
{
int ch = 0;//ch is the cast
int lines = 0;//start with one because
if (input_file == NULL)
return 0;
while (!feof(input_file))
{
ch = fgetc(input_file);
if (ch == '\n')
{
lines++;
}
}//end while
printf("lines: %d\n", lines);
}//end while loop
while (fgets(line, LINE_LENGTH, input_file) != NULL)
{
int ch = 0;//ch is the cast
int lines = 0;//start with one because
if (input_file == NULL)
return 0;
while (!feof(input_file))
{
int characters = 0;
char c;
for (c = getc(input_file); c != EOF; c = getc(input_file))
// Increment count for this character
characters = characters + 1;
printf("characters: %d\n", characters);
fclose(input_file);
}
}
}
this is my first Question here so im grateful for every kind of Help.
Im trying to get the length of the longest Line in a File, so i can later calloc it and read the whole File in. My first attempt was Dynamic, but it didnt work.
My Code till now is:
FILE *inputData;
inputData = fopen("input.txt", "r");
char *input = NULL;
int longestLinelength = 0;
while(fscanf(inputData,"%[^\n]", input) != EOF) {
if(longestLineLength<strlen(input)){
longestLineLength=strlen(input);
}
}
fclose()
This code unfortunetly leads to a memory access error.
size_t longestLine(FILE *fi)
{
size_t largest = 0, current = 0;
int ch;
if(fi)
{
while((ch = fgetc(fi)) != EOF)
{
if(ch == '\n')
{
if(current > largest) largest = current;
current = 0;
}
else
{
current++;
}
}
if(current > largest) largest = current;
}
return largest;
}
I think the problem is not with realloc, but with a misunderstanding of how things work.
It would be best to read carefully what scanf does. And how pointers work.
input is a NULL pointer and you want to write to it, this causes a crash in the application. scanf needs allocated memory to write to, it does not allocate it itself. Generally I would suggest to use fgets instead of scanf as it is better to handle. The formating options of scanf can be done after you read it with fgets.
Probably this help this is based on the book The C Programming Language.
First we need a main function to get the lines in the file
int get_file_line(char line[], int maxline, FILE *fptr) {
int ch, i;
for (i = 0; i < (maxline - 1) && ((ch = getc(fptr)) != EOF) && (ch != '\n'); ++i) {
line[i] = ch;
}
if (ch == '\n') {
line[i] = ch;
++i;
}
line[i] = '\0';
return i;
}
Then we will store the data into a new array of chars
void copy(char to[], char from[]) {
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
i++;
}
}
And finally in the main function we gonna open the file and use the previous functions
FILE *ptr;
const char *file_name = "your_file.txt";
ptr = fopen(file_name, "r");
while ((len = get_file_line(line, MAXLINE, ptr)) > 0) {
if (len > max) {
max = len;
copy(longest, line);
}
}
fclose(ptr);
if (max > 0) {
printf("longest: %s\n", longest);
printf("len : %d\n", max);
}
All together
#include <stdio.h>
#define MAXLINE 1000
int get_file_line(char line[], int maxline, FILE *fptr) {
int ch, i;
for (i = 0; i < (maxline - 1) && ((ch = getc(fptr)) != EOF) && (ch != '\n'); ++i) {
line[i] = ch;
}
if (ch == '\n') {
line[i] = ch;
++i;
}
line[i] = '\0';
return i;
}
void copy(char to[], char from[]) {
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
i++;
}
}
int main() {
int len, max = 0;
char line[MAXLINE];
char longest[MAXLINE];
FILE *ptr;
const char *file_name = "your_file.txt";
ptr = fopen(file_name, "r");
while ((len = get_file_line(line, MAXLINE, ptr)) > 0) {
if (len > max) {
max = len;
copy(longest, line);
}
}
fclose(ptr);
if (max > 0) {
printf("longest: %s\n", longest);
printf("len : %d\n", max);
}
return 0;
}
I hope this was helpful
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 4096
static void process_file(char *filename);
int main(int argc, char **argv) {
int q;
if(argc <= 1) {
printf("Usage: %s <files>\n", argv[0]);
return 1;
}
for(q = 1; q < argc; q++) {
process_file(argv[q]);
}
return 0;
}
void process_file(char *filename) {
char buf[MAX_LINE_LENGTH] = {0};
FILE *file;
char line_val[MAX_LINE_LENGTH] = {0};
int line_len = -1;
int line_num = -1;
int cur_line = 1;
file = fopen(filename, "r");
if(file == NULL) {
return;
}
while(fgets(buf, MAX_LINE_LENGTH, file) != NULL) {
int len_tmp = strlen(buf) - 1;
if(buf[len_tmp] == '\n')
buf[len_tmp] = '\0';
if(line_len < len_tmp) {
strncpy(line_val, buf, len_tmp + 1);
line_len = len_tmp;
line_num = cur_line;
}
cur_line++;
/*printf("%s", buf);*/
}
fclose(file);
if(line_num < 1) {
return;
}
printf("%d:%s:%d:%s\n", line_len, filename, line_num, line_val);
}
I have used comma as a separator after every string
fp=fopen("log.dat","ab");
fprintf(fp,"%s%c",enteredUsername,',');
fclose(fp);
Reading from file:
fp=fopen("log.dat","rb");
int c;
while ((c = fgetc(fp)) != EOF)
printf("%c", c);
How can I:
1.Avoid reading the final character inside the file,
2.Check if file is empty?
You can use a one-character buffer like this:
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("log.dat", "rb");
if(fp == NULL) return;
int prev = -1000;
int c;
while ((c = fgetc(fp)) != EOF) {
if(prev >= 0) {
printf("%c", prev);
}
prev = c;
}
fclose(fp);
return 0;
}
Input log.dat
one,two,three,
Output
one,two,three
Why you want to avoid reading the final character? You can use the EOF in order to check if a file is empty.
if( (c= fgetc(fp)) == EOF){
//do stuff
}
else{
printf("File is empty\n")
return 0;
}
That worked for me.
#include <stdio.h>
int main(void) {
unsigned counter;
for( counter=0; 1; counter++) {
int ch;
char lastchar;
ch = getc(stdin);
if (ch == EOF) break;
if (counter) putc( lastchar, stdout);
lastchar = ch;
}
if (!counter) fprintf(stderr,"File was empty\n" );
else fprintf(stderr,"Read %u characters.\n", counter );
return 0;
}
// Test it with:
// echo -n "a,b,c," >bagger
// ./a.out <bagger
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
I need to create a function that finds the most common letter in a file using C.
Can't figure out my problem, for some reason it always returns [.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char commonestLetter(char* filename);
void main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
fclose(fout);
}
printf("Enter string (to be written on file)\n");
gets(str);
fputs(str, fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
fclose(fout);
}
char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}
for (i = 0; i < 26; i++)
count[i] = 0;
while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}
for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i + 1;
}
}
return location + 'A';
}
Do
location=i;
No need of i+1
As you are doing location+'A';
Suppose the location count[25] has the highest count, so the location becomes 25+1=26.
Now the return will be 26+65=91 which is of '['
The code of yours is slightly modified but the logic of your is kept
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char commonestLetter(char* filename);
int main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
return 0;
}
printf("Enter string (to be written on file): ");
fgets(str,sizeof(str),stdin);
fputs(str, fout);
fclose(fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
return 0;
}
char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}
memset(&count,0,sizeof(count));
while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}
for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i;
}
}
fclose(f);
return location + 'A';
}
Input & Output:
Enter string (to be written on file): Gil this is a testing
The most common letter is I
The problem here is, in your code,
location = i + 1;
location is i+1 at the end, and you're returning location + 'A'; which is (because of your input, probably) (25+1) + 'A' , i.e., 26 + 'A' which is [.